mirror of
https://github.com/Swiftgram/Telegram-iOS.git
synced 2025-06-16 05:55:20 +00:00
44 lines
996 B
Swift
44 lines
996 B
Swift
import Foundation
|
|
|
|
public final class Atomic<T> {
|
|
private var lock: pthread_mutex_t
|
|
private var value: T
|
|
|
|
public init(value: T) {
|
|
self.lock = pthread_mutex_t()
|
|
self.value = value
|
|
|
|
pthread_mutex_init(&self.lock, nil)
|
|
}
|
|
|
|
deinit {
|
|
pthread_mutex_destroy(&self.lock)
|
|
}
|
|
|
|
public func with<R>(_ f: (T) -> R) -> R {
|
|
pthread_mutex_lock(&self.lock)
|
|
let result = f(self.value)
|
|
pthread_mutex_unlock(&self.lock)
|
|
|
|
return result
|
|
}
|
|
|
|
public func modify(_ f: (T) -> T) -> T {
|
|
pthread_mutex_lock(&self.lock)
|
|
let result = f(self.value)
|
|
self.value = result
|
|
pthread_mutex_unlock(&self.lock)
|
|
|
|
return result
|
|
}
|
|
|
|
public func swap(_ value: T) -> T {
|
|
pthread_mutex_lock(&self.lock)
|
|
let previous = self.value
|
|
self.value = value
|
|
pthread_mutex_unlock(&self.lock)
|
|
|
|
return previous
|
|
}
|
|
}
|