swift - 首次调用信号时如何使用 Dispatch_Sempahore
问题描述
在 DispatchSemaphore 函数中,可以先调用 Signal() 再调用 Wait() 吗?如果连续调用Signal() N,内部的值是不是变成了N,或者我想知道如果不调用Wait(),多次调用Signal()不会增加值。
let sempahore = DispatchSemaphore(value: 0)
semaphore.signal()
semaphore.signal()
semaphore.signal()
// in time, what is sempahore value? 1 or 3?
sempahore.wait()
// in time, what is semaphore value? 0 or 2?
// wait for more signal? or not?
解决方案
每一个.signal
都是'+1',每一个.wait
都是'-1'或block
如记录的那样,演示的代码是
let semaphore = DispatchSemaphore(value: 0)
semaphore.signal() // = 1
semaphore.signal() // = 2
semaphore.signal() // = 3
semaphore.wait() // = 2 - pass
semaphore.wait() // = 1 - pass
semaphore.wait() // = 0 - pass
semaphore.wait() // = -1 - hang - waiting for new signal()
这是来自Apple 文档
您可以通过调用 signal() 方法来增加信号量计数,并通过调用 wait() 或其指定超时的变体之一来减少信号量计数。
@discardableResult func signal() -> Int Discussion Increment the counting semaphore. If the previous value was less than zero, this function wakes a thread currently waiting func wait() Discussion Decrement the counting semaphore. If the resulting value is less than zero, this function waits for a signal to occur before returning.
推荐阅读
- c# - 如何从 Winform 中清除用户控件?
- google-cloud-platform - 增加同时远程桌面 (TS) 连接的数量
- excel - 目标范围。以空格结尾
- linux - 如果 shell 脚本运行时间长,则通知
- c - 致命错误:interrupt.h:没有这样的文件或目录#include
- jquery - 如何制作简单的 div 框中继器 jquery?
- prolog - 网格中的 Prolog 检查元素
- python - 如何在 peewee 中的计算字段上创建索引
- laravel - 检查唯一性 - laravel
- python - Python Discord Bot - Youtube-dl 未使用完整搜索查询进行搜索