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

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.

主站蜘蛛池模板: 饶阳县| 施秉县| 依安县| 大渡口区| 崇文区| 高安市| 佛冈县| 石柱| 石狮市| 德庆县| 新野县| 天峻县| 娱乐| 普陀区| 松江区| 小金县| 绥芬河市| 赤水市| 孝昌县| 广宗县| 仁寿县| 广宗县| 屏东市| 江山市| 衡山县| 东乌珠穆沁旗| 洪泽县| 林周县| 津市市| 股票| 历史| 冀州市| 沂源县| 靖西县| 玉田县| 丹巴县| 呼图壁县| 永吉县| 观塘区| 湾仔区| 马龙县|