pthread_cond_broadcast前后一pthread_mutex_unlock

pthread_cond_broadcast before and after one pthread_mutex_unlock

对于下面的代码,互斥锁在执行秒 cond_broadcast 时不可用(假设多个线程已经在等待条件)。在这种情况下,广播 select 线程(等待条件)是否将互斥体交给其他线程并等待互斥体被其他线程解锁,或者第二个 cond_broadcast 被忽略?

void* func(void* arg){
pthread_mutex_lock(&m);
while(condition){
pthread_cond_wait(&c,&m);
}
pthread_cond_broadcast(&c);
pthread_mutex_unlock(&m);
pthread_cond_broadcast(&c);
}

For the code below, the mutex will not available by the time second cond_broadcast is executed(assuming multiple threads already waiting on the condition).

我认为您的意思是在第二次调用该函数时调用 pthread_cond_broadcast() 的线程将无法使用互斥锁,但这无关紧要。调用 pthread_cond_broadcast() 与持有任何互斥体无关。

或者您的意思可能是先前阻塞的线程之一将在第二次广播发生时获得互斥量,但是 (1) 不确定,并且 (2) 如果确实发生,那没有特别的关于广播的重要性。

In such situation, does the broadcast select the thread(waiting on the condition) to hand the mutex to and wait for the mutex to be unlocked by some other thread or the second cond_broadcast is just ignored?

都没有。 pthread_cond_broadcast()pthread_cond_signal() 在锁定或转移任何互斥锁的控制方面没有任何作用。它们只是唤醒在相关 CV 上阻塞的线程。每个这样的线程都必须在 return 从调用中获取互斥锁是一个单独的考虑因素——它们通常都争用锁定互斥锁,并且它们不会 return 从 pthread_cond_wait() 直到它们做。他们也不会在没有先 return 退出等待然后再次调用 pthread_cond_wait() 的情况下返回等待。

但这并不意味着您代码中的第二个 pthread_cond_broadcast() 一定没有效果。刚刚唤醒的线程之一可能会循环并在两次调用之间再次等待 CV,或者某个其他线程可能会到达 CV。一旦第一个线程释放互斥量,这就成为可能,并且线程尝试做的第一件事是另一个广播这一事实并不能确保广播在另一个线程可以开始等待之前发生。

你不太可能像那样一个接一个地想要两个广播,但你保留哪个对节目的整体语义影响很小,如果有的话。