我有下面的代码来同步多个线程。在下面的代码中,创建16个线程时,看起来只有1个等待成功;4个线程正在等待;11个线程不需要等待(因为标志已设置为1)。
你能看看问题出在哪里吗?谢谢!
static int can_go = 0;
static pthread_mutex_t go_mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t wait_cond = PTHREAD_COND_INITIALIZER;
void set_go( void )
{
pthread_mutex_lock( &go_mtx );
can_go = 1;
pthread_cond_signal(&wait_cond);
pthread_mutex_unlock( &go_mtx );
}
int wait_go( void )
{
pthread_mutex_lock( &go_mtx );
while(can_go == 0)
{
printf("beging waiting ... \n");
pthread_cond_wait(&wait_cond, &go_mtx);
printf("waiting done\n");
}
printf("outside of while waiting !!!\n");
pthread_mutex_unlock( &go_mtx );
}
然后我的main()创建了16个线程,在每个线程中,我做了:
void *run_thread(viod *ptr)
{
..............
if (is_sync_thread){ //if this is a special sync thread, do something and trigger other threads
.............
set_go();
}
else{ //this is worker, wait for sync thread finish and set_go()
wait_go()
....................
}
}
这是输出:
beging waiting ...
beging waiting ...
beging waiting ...
beging waiting ...
beging waiting ...
wait done
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
最佳答案
您调用了pthread_cond_signal
,这只保证唤醒一个线程。您需要pthread_cond_broadcast
,它保证唤醒所有等待的线程。
关于c - 它是如何工作的? pthread_cond_signal()和pthread_cond_wait(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32261365/