以下 swift 代码应该永远阻塞 - pthread_cond_wait
应该永远不会返回,因为没有人发出信号。
当我运行它时 - 它会按预期阻塞。
如果我使用 Xcode 9 (9.0.1) 设置断点,执行会继续到 print("hi")
行。
这是一个奇怪的 Xcode 错误还是我做错了什么?
import Foundation
func check(_ ret:Int32){
if ret != 0 {
fatalError("Error \(ret)")
}
}
var cond = pthread_cond_t()
pthread_cond_init(&cond,nil)
var mutex = pthread_mutex_t()
check(pthread_mutex_init(&mutex,nil))
check(pthread_mutex_lock(&mutex))
check(pthread_cond_wait(&cond,&mutex))
print("Hi")
check(pthread_mutex_unlock(&mutex))
还检查了 pthread_cond_timedwait
,同样的行为。
最佳答案
pthread_cond_wait
可以有 spurious wakeups . POSIX 对此非常明确:
When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.
似乎在您的环境中,在调试器下运行会导致此类唤醒发生,这可能是由于调试器触发的额外信号。如果调试器以这种方式影响应用程序行为,那肯定很烦人,但从技术上讲,这不是错误。
关于swift - 如果使用 Xcode 9 设置断点,为什么 pthread_cond_wait 会返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46892256/