等待所有子线程运行

等待所有线程运行起来,其代码如下所示:

主线程代码:

static int init_count = 0;
static pthread_mutex_t init_lock;
static pthread_cond_t init_cond;   

 /* Wait for all the threads to set themselves up before returning. */
    pthread_mutex_lock(&init_lock);
    wait_for_thread_registration(nthreads); //主线程阻塞等待事件到来
    pthread_mutex_unlock(&init_lock);

work线程代码:

/*
即主线程阻塞如此,等待worker_libevent发出的init_cond信号,唤醒后检查init_count < nthreads是否为假
(即创建的线程数目是否达到要求),否则继续等待。
*/
static void wait_for_thread_registration(int nthreads) {
    while (init_count < nthreads) {
        pthread_cond_wait(&init_cond, &init_lock);
    }
}

//结合wait_for_thread_registration使用,保证子线程先运行起来
static void register_thread_initialized(void) {
    pthread_mutex_lock(&init_lock);
    init_count++;
    pthread_cond_signal(&init_cond);
    pthread_mutex_unlock(&init_lock);
}

 

posted @ 2022-09-15 22:25  codestacklinuxer  阅读(24)  评论(0)    收藏  举报