简体   繁体   English

调用pthread_cond_broadcast后为什么不调用pthread_cond_wait?

[英]why doesn`t calling pthread_cond_wait return immediately after calling pthread_cond_broadcast?

The title basically speaks for itself.After sleeping for 5 sec and unlocking the mutex,it finally return from pthread_cond_wait. 标题基本上不言自明。在睡眠5秒并解锁互斥锁后,它最终从pthread_cond_wait返回。 It seems like pthread_cond_wait knows that it can`t get the mutex,so it waits,after unlocking the mutex, pthread_cond_wait gets the mutex,then goes on.. is that so? 似乎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 );
}

The pthread_cond_wait function releases the mutex while it waits and then returns with the mutex acquired again. pthread_cond_wait函数在等待时释放互斥锁,然后再次获取互斥锁返回。 If another thread holds the mutex, then that thread can't resume execution until the mutex is released. 如果另一个线程持有互斥锁,则该线程在释放互斥锁之前无法继续执行。 If this causes a problem for you, you're using condition variables incorrectly. 如果这对您造成问题,则表示您正在错误地使用条件变量。

The mutex needs to be released while the thread is waiting, otherwise other threads couldn't acquire it. 在线程等待时需要释放互斥锁,否则其他线程无法获取它。 The mutex needs to be re-acquired before returning -- if for no other reason, to allow the thread to check if it needs to call pthread_cond_wait again. 在返回之前需要重新获取互斥锁 - 如果没有其他原因,允许线程检查是否需要再次调用pthread_cond_wait

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM