本文介绍了调用pthread_cond_signal而不锁定互斥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我读了某个地方,在调用 pthread_cond_signal 之前应该锁定 mutex ,并在调用它后解锁mutext: pthread_cond_signal()例程是,用来发送(或唤醒)另一个正在等待条件变量的线程。它应该是调用mutex锁定后,必须解锁互斥为了 pthread_cond_wait()例程到完成。 我的问题是:在不锁定互斥体的情况下调用 pthread_cond_signal 或 pthread_cond_broadcast 解决方案如果你不锁定互斥体在改变条件和信号的代码路径,你可以失去唤醒。考虑这对过程: 过程A: code> pthread_mutex_lock(& mutex); while(condition == FALSE) pthread_cond_wait(& cond,& mutex); pthread_mutex_unlock(& mutex); 处理B(不正确): condition = TRUE; pthread_cond_signal(& cond);然后考虑这种可能的指令插入,其中条件开始为 FALSE : $ b pthread_mutex_lock(& mutex); while(condition == FALSE) condition = TRUE; pthread_cond_signal(& cond); pthread_cond_wait(& cond,& mutex); 条件现在 TRUE ,但进程A卡在等待条件变量 - 它错过了唤醒信号。如果我们更改进程B以锁定互斥体: 进程B(正确): pthread_mutex_lock(& mutex); condition = TRUE; pthread_cond_signal(& cond); pthread_mutex_unlock(& mutex); ...然后上述不能发生; (请注意,您 实际上可以移动 pthread_cond_signal()自己在 pthread_mutex_unlock()之后,但是这可能导致线程的优化调度较少,并且您必须锁定互斥体已经在此代码路径中,条件本身)。 I read somewhere that we should lock the mutex before calling pthread_cond_signal and unlock the mutext after calling it: The pthread_cond_signal() routine is used to signal (or wake up) another thread which is waiting on the condition variable. It should be called after mutex is locked, and must unlock mutex in order for pthread_cond_wait() routine to complete.My question is: isn't it OK to call pthread_cond_signal or pthread_cond_broadcast methods without locking the mutex? 解决方案 If you do not lock the mutex in the codepath that changes the condition and signals, you can lose wakeups. Consider this pair of processes:Process A:pthread_mutex_lock(&mutex);while (condition == FALSE) pthread_cond_wait(&cond, &mutex);pthread_mutex_unlock(&mutex);Process B (incorrect):condition = TRUE;pthread_cond_signal(&cond);Then consider this possible interleaving of instructions, where condition starts out as FALSE:Process A Process Bpthread_mutex_lock(&mutex);while (condition == FALSE) condition = TRUE; pthread_cond_signal(&cond);pthread_cond_wait(&cond, &mutex);The condition is now TRUE, but Process A is stuck waiting on the condition variable - it missed the wakeup signal. If we alter Process B to lock the mutex:Process B (correct):pthread_mutex_lock(&mutex);condition = TRUE;pthread_cond_signal(&cond);pthread_mutex_unlock(&mutex);...then the above cannot occur; the wakeup will never be missed.(Note that you can actually move the pthread_cond_signal() itself after the pthread_mutex_unlock(), but this can result in less optimal scheduling of threads, and you've necessarily locked the mutex already in this code path due to changing the condition itself). 这篇关于调用pthread_cond_signal而不锁定互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-29 14:39