官术网_书友最值得收藏!

Thread safety through serial queues

Sometimes, in your code, you want to guarantee that no two concurrent threads will write to the same memory. You can use the @synchronized(self) section in Objective-C, but in Swift, you can leverage Dispatch and serial queues. As you saw in the previous section, the execution order will be preserved, as well as additional guarantees that the previous task enqueued on a serial queue will be completed before the next one starts.

You can ensure that access to the balance property of CreditCard is thread-safe, which guarantees that no other thread or code is writing while you are reading the value:

class CreditCard {
private let queue = DispatchQueue(label: "synchronization.queue")
private var _balance: Int = 0
var balance: Int {
get {
return queue.sync { _balance }
}
set {
queue.sync { _balance = newValue }
}
}
}

In the preceding example, we use a shadow variable (balance) to provide public access to the underlying _balance. The shadow variable will guarantee that the _balance object/variable will always be accessed in a thread safe manner.

主站蜘蛛池模板: 遂川县| 呼图壁县| 济南市| 通州市| 确山县| 合阳县| 东乡| 太仓市| 云和县| 芜湖市| 德清县| 仙游县| 利辛县| 鄢陵县| 荥经县| 磐安县| 休宁县| 潢川县| 青田县| 朝阳区| 水富县| 清丰县| 伊春市| 阿荣旗| 龙陵县| 浙江省| 海晏县| 蒙城县| 罗江县| 汤阴县| 深水埗区| 北碚区| 静宁县| 盐亭县| 谢通门县| 永康市| 宜章县| 渭南市| 卓尼县| 杭锦旗| 永宁县|