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

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.

主站蜘蛛池模板: 安乡县| 资兴市| 舒兰市| 西藏| 靖安县| 夏邑县| 翁源县| 成武县| 漠河县| 浪卡子县| 南川市| 广东省| 五寨县| 宁陕县| 内黄县| 桦川县| 宣武区| 泾川县| 景谷| 南华县| 平江县| 满洲里市| 虞城县| 芦溪县| 永平县| 晋州市| 中阳县| 十堰市| 当雄县| 三河市| 山东省| 亚东县| 库伦旗| 新乡市| 安乡县| 周宁县| 百色市| 镇坪县| 保亭| 满城县| 吉水县|