标题基本上不言自明。在睡眠5秒后解锁互斥锁后,它最终从pthread_cond_wait返回。似乎pthread_cond_wait知道它不能获取互斥锁,所以等待,在解锁互斥锁之后,pthread_cond_wait获取互斥锁,然后继续......是这样的吗?
#include <pthread.h>
pthread_mutex_t alarm_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t alarm_cond = PTHREAD_COND_INITIALIZER;
int s_i = 0;
void* alarm_thread ( void* arg )
{
pthread_mutex_lock ( &alarm_mutex );
while ( 1 )
{
while ( s_i == 1 )
{
pthread_cond_wait ( &alarm_cond, &alarm_mutex );
printf("I am here");
}
}
}
int main ( int argc, char* argv[] )
{
pthread_t thread;
pthread_create ( &thread, NULL, alarm_thread, NULL );
pthread_mutex_lock ( &alarm_mutex );
s_i = 1;
pthread_cond_broadcast ( &alarm_cond );
sleep ( 5 );
pthread_mutex_unlock ( &alarm_mutex );
}
答案 0 :(得分:2)
pthread_cond_wait
函数在等待时释放互斥锁,然后再次获取互斥锁返回。如果另一个线程持有互斥锁,则该线程在释放互斥锁之前无法继续执行。如果这对您造成问题,则表示您正在错误地使用条件变量。
在线程等待时需要释放互斥锁,否则其他线程无法获取它。在返回之前需要重新获取互斥锁 - 如果没有其他原因,允许线程检查是否需要再次调用pthread_cond_wait
。