标题基本上不言自明。在休眠 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 );
}