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

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.

主站蜘蛛池模板: 昌黎县| 吴江市| 丰顺县| 安国市| 宁武县| 香格里拉县| 芷江| 牙克石市| 横山县| 贵州省| 和政县| 平遥县| 大渡口区| 海城市| 南充市| 玛纳斯县| 临夏市| 镇远县| 天津市| 子长县| 晋宁县| 南投市| 涟源市| 龙口市| 抚顺市| 馆陶县| 翁源县| 青海省| 杭锦后旗| 靖州| 元阳县| 利川市| 香格里拉县| 山阳县| 凯里市| 望江县| 高邮市| 望城县| 酉阳| 江安县| 肇庆市|