Atomic 是一个用于在 Swift 中使值线程安全的高速、安全类。它由 pthread_mutex_lock
支持,这是最快速、最高效的锁定机制。
pod Atomic
来使用 CocoaPods。github "Adlai-Holler/Atomic"
来使用 Carthage。/// This class is completely thread-safe (yay!).
final class MyCache<Value> {
private let entries: Atomic<[String: Value]> = Atomic([:])
func valueForKey(key: String) -> Value? {
return entries.withValue { $0[key] }
}
func setValue(value: Value, forKey: Key) {
entries.modify { (var dict) in
dict[key] = value
return dict
}
}
func clear() {
entries.value = [:]
}
func copy() -> [String: Value] {
return entries.value
}
}
/// Thread-safe manager for the `networkActivityIndicator` on iOS.
final class NetworkActivityIndicatorManager {
static let shared = NetworkActivityIndicatorManager()
private let count = Atomic(0)
func incrementActivityCount() {
let oldValue = count.modify { $0 + 1 }
if oldValue == 0 {
updateUI(true)
}
}
func decrementActivityCount() {
let oldValue = count.modify { $0 - 1 }
if oldValue == 1 {
updateUI(false)
}
}
private func updateUI(on: Bool) {
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
}
}
pthread_mutex_lock
比起 NSLock
快,比 OSSpinLock
高效。throw
错误,采用 @noescape
和泛型来使您的代码尽可能简洁。Atomic.swift
的原始版本是由 ReactiveCocoa 贡献者编写的。