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

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.

主站蜘蛛池模板: 黑龙江省| 九江市| 东莞市| 友谊县| 繁昌县| 托里县| 双城市| 杨浦区| 焉耆| 贵南县| 石林| 万年县| 瑞丽市| 顺昌县| 北辰区| 吉首市| 额敏县| 五台县| 江永县| 万全县| 苍梧县| 准格尔旗| 巴东县| 和政县| 富锦市| 平湖市| 兴山县| 托克托县| 安福县| 连州市| 沅江市| 于田县| 广灵县| 讷河市| 深水埗区| 天气| 墨竹工卡县| 古交市| 河西区| 于田县| 余干县|