它是如何工作的? pthread_cond_signal()和pthread_cond_wait()

时间:2015-08-28 00:04:44

标签: c linux multithreading

我有以下代码来同步多个线程。在下面的代码中,创建16个线程,看起来只有1个等待成功; 4正在保持徘徊; 11不需要等待(因为标志已设置为1)。

请你看一下,看看问题出在哪里?谢谢!

.center-logo {
  position: absolute;  
  display: block;
}

然后我的main()创建了16个线程,在每个线程中,我做了:

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 );
}

这是输出:

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()
        ....................
    }   
}

1 个答案:

答案 0 :(得分:4)

您调用pthread_cond_signal,只保证唤醒一个线程。你想要pthread_cond_broadcast,这可以保证唤醒所有等待的线程。