多线程:条件变量使用的两个注意事项

条件变量是一种同步机制,允许线程挂起,直到共享数据上的某些条件得到满足。条件变量上的基本操作有:触发条件(当条件变为 true 时);等待条件,挂起线程直到其他线程触发条件

  1. while ()为什么是while而不是if?
    因为可能会有虚假唤醒的问题。

    "This means that when you wait on a condition variable, the wait may (occasionally) return when no thread specifically broadcast or signaled that condition variable. Spurious wakeups may sound strange, but on some multiprocessor systems, making condition wakeup completely predictable might substantially slow all condition variable operations. The race conditions that cause spurious wakeups should be considered rare."

  2. pthread_cond_signalpthread_mutex_unlock的调用顺序是否可以交换
    不可以
    不必考虑性能损耗

    在Linux线程调度实现中,有两个队列,分别是cond_wait队列和mutex_lock队列, pthread_cond_signal只是让线程从cond_wait队列移到mutex_lock队列,并没有真正的执行线程切换,没有性能消耗。在iOS里面也是推荐pthread_cond_signalpthread_mutex_unlock之前调用的

    有可能锁被其他线程获取

参考

posted on 2018-01-07 10:41  花老🐯  阅读(244)  评论(0编辑  收藏  举报

导航