从Low-Level Concurrency APIs开始:
有一长串的OSAtomicIncrement和OsatomicDecretion
这些函数使用固定大小的整数,您可以 Select
class Counter {
private (set) var value : Int32 = 0
func increment () {
OSAtomicIncrement32(&value)
}
}
(Note:正如埃里克·艾格纳正确地注意到的,OSAtomicIncrement32
和
或者,可以使用GCD队列进行同步.
... 使用调度队列,您可以将这两个任务添加到串行队列中
对你来说那就是
// Swift 2:
class Counter {
private var queue = dispatch_queue_create("your.queue.identifier", DISPATCH_QUEUE_SERIAL)
private (set) var value: Int = 0
func increment() {
dispatch_sync(queue) {
value += 1
}
}
}
// Swift 3:
class Counter {
private var queue = DispatchQueue(label: "your.queue.identifier")
private (set) var value: Int = 0
func increment() {
queue.sync {
value += 1
}
}
}
See Adding items to Swift array across multiple threads causing issues (because arrays aren't thread safe) - how do I get around that? or GCD with static functions of a struct for more sophisticated examples. This thread
What advantage(s) does dispatch_sync have over @synchronized? is also very interesting.