- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 180字
- 2021-07-02 14:45:11
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.
- 計算機組成原理與接口技術(shù):基于MIPS架構(gòu)實驗教程(第2版)
- PyTorch深度學習實戰(zhàn):從新手小白到數(shù)據(jù)科學家
- 數(shù)據(jù)分析實戰(zhàn):基于EXCEL和SPSS系列工具的實踐
- 數(shù)據(jù)可視化:從小白到數(shù)據(jù)工程師的成長之路
- 信息系統(tǒng)與數(shù)據(jù)科學
- 計算機信息技術(shù)基礎(chǔ)實驗與習題
- Voice Application Development for Android
- 大數(shù)據(jù):從概念到運營
- 智能數(shù)據(jù)時代:企業(yè)大數(shù)據(jù)戰(zhàn)略與實戰(zhàn)
- 網(wǎng)站數(shù)據(jù)庫技術(shù)
- SQL優(yōu)化最佳實踐:構(gòu)建高效率Oracle數(shù)據(jù)庫的方法與技巧
- 數(shù)據(jù)科學工程實踐:用戶行為分析與建模、A/B實驗、SQLFlow
- 爬蟲實戰(zhàn):從數(shù)據(jù)到產(chǎn)品
- Python數(shù)據(jù)分析從小白到專家
- Expert Python Programming(Third Edition)