- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 191字
- 2021-07-02 14:45:12
Example of a counting semaphore
In the following example, we'll use a semaphore to suspend the execution of the current thread until a long-running task has completed:
let semaphore = DispatchSemaphore(value: 0)
let queue = DispatchQueue(label: "com.run.concurrent",
attributes: .concurrent)
// Run a block 1 second of the future
queue.asyncAfter(deadline: DispatchTime.now() + 1) {
print("Will Signal")
semaphore.signal()
print("Did Signal")
}
print("Will Wait")
// wait for the semaphore, this suspends the current thread
semaphore.wait()
print("Done")
This will give us the following output:
Will Wait
Will Signal
Did Signal
Done
As you can see, this code successfully waited till the long-running operation was done, and signal() has been called on the semaphore.
Note that blocking the main thread with a semaphore may result in a deadlock if the semaphore is expected to be signaled on the main thread.
While semaphores are very powerful tools for coordinating the execution of many threads, sometimes, you may not know how many tasks you'll need to synchronize. Also, with semaphores, it is very easy to deadlock a thread as to continue execution; you'll need to balance all wait calls with signal calls. DispatchGroups are suited for this task.
推薦閱讀
- 程序員修煉之道:從小工到專家
- 數(shù)據(jù)庫應(yīng)用實(shí)戰(zhàn)
- Python廣告數(shù)據(jù)挖掘與分析實(shí)戰(zhàn)
- 數(shù)據(jù)驅(qū)動(dòng)設(shè)計(jì):A/B測試提升用戶體驗(yàn)
- 跟老男孩學(xué)Linux運(yùn)維:MySQL入門與提高實(shí)踐
- gnuplot Cookbook
- Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第3版)
- 企業(yè)級容器云架構(gòu)開發(fā)指南
- Instant Autodesk AutoCAD 2014 Customization with .NET
- Visual Studio 2013 and .NET 4.5 Expert Cookbook
- 大數(shù)據(jù)技術(shù)原理與應(yīng)用:概念、存儲、處理、分析與應(yīng)用
- 大數(shù)據(jù)數(shù)學(xué)基礎(chǔ)(R語言描述)
- 機(jī)器學(xué)習(xí):實(shí)用案例解析
- 數(shù)據(jù)中臺實(shí)戰(zhàn):手把手教你搭建數(shù)據(jù)中臺
- 大數(shù)據(jù)計(jì)算系統(tǒng)原理、技術(shù)與應(yīng)用