【问题标题】:pthread_cond_wait without a while looppthread_cond_wait 没有 while 循环
【发布时间】:2012-05-22 15:32:39
【问题描述】:
global variable 'temp';

**threadA**   
    -pthread_mutex_lock-  
            if (temp == 'x')  
                    -pthread_cond_wait-
                    do this     
        -pthread_mutex_unlock-      

**threadB**  
    -pthread_mutex_lock-  
            if (someCondition == true)            
                        temp = 'x'  
                -pthread_cond_signal-  
    -pthread_mutex_unlock-

就我而言,我可能没有任何循环,我只有一个 if 条件。所以,我希望当 temp == 'x' 时,threadA 应该这样做/这个。

  • 在处理pthread_cond_wait 时是否必须使用循环?
  • 如果我们不需要循环,编写代码的另一种方法是什么?
  • 这是一种正确的代码编写方式吗?

【问题讨论】:

    标签: multithreading pthreads mutex condition-variable


    【解决方案1】:

    循环是强制性的,因为根据http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_wait.html:

    可能会发生来自 pthread_cond_timedwait() 或 pthread_cond_wait() 函数的虚假唤醒。由于 pthread_cond_timedwait() 或 pthread_cond_wait() 的返回并不暗示此谓词的值,因此应在返回时重新评估谓词。

    【讨论】:

    • “可能会发生来自 pthread_cond_timedwait() 或 pthread_cond_wait() 函数的虚假唤醒。” 这是否意味着唤醒可能会无故自动发生?
    • 是的,这就是标准所说的——特定的实现可能会选择实现更严格的语义。
    猜你喜欢
    • 1970-01-01
    • 2019-10-11
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多