使用 pthread_cond_wait 的最佳情况

Best situations of using pthread_cond_wait

我想在事件发生时同步两个线程,我发现许多资源建议在这种情况下使用 pthread_cond 但是我看不出 pthread_condpthread_cond 之间的区别mutexes:

我们可以使用下面的代码:

// thread 1 waiting on a condition
while (!exit)
{
   pthread_mutex_lock(&mutex); //mutex lock
   if(condition)
     exit =  true;
   pthread_mutex_unlock(&mutex);
}
... reset condition and exit

// thread 2 set condition if an event occurs
pthread_mutex_lock(&mutex); //mutex lock
 condition = true;
pthread_mutex_unlock(&mutex);

而不是:

//thread 1: waiting on a condition
pthread_mutex_lock(&mutex);
while (!condition)
    pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);

//thread 2: signal the event 
pthread_mutex_lock(&mutex);
condition = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);

你能帮我理解我们必须使用 pthread_cond

的最佳实践/情况吗

您的第一个示例将一直旋转并使用 CPU,而等待条件变量将暂停进程,并且在条件变量发出信号之前不会 运行。如果在第一个示例中,机器中只有一个 CPU,线程 1 也可能会长时间阻塞来自 运行ning 的线程 2,因此它甚至没有机会发出条件信号.

旋转是浪费 CPU 时间,浪费电力,最终可能会慢很多数量级。

(你的第二个例子确实有一个错误,但我很确定这只是编造例子时的一个错误,这就是为什么在问题)