swift - 如果使用 Xcode 9 设置断点,为什么 pthread_cond_wait 会返回?

标签 swift xcode pthreads

以下 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/

相关文章:

ios - swift : Use of instance member on type 'ViewController' ; did you mean to use a value of type 'ViewController' instead

ios - layer.cornerRadius 不能与 NSLayoutConstraints 结合使用(swift 3)

c - pthread_join() 导致段错误

ios - 舍入 UITableViewCell

ios - 强制 iOS 通知显示警报按钮,无需滑动或强制触摸

Swift 如何将 Parse createdAt 时间转换为时间前?

ios - Crashlytics奇怪的崩溃报告-com.apple.main-thread。 EXC_BREAKPOINT

ios - 运行脚本错误: No such file or directory

c - pthread_cancel 不起作用

c++ - C++中的Pthread取消