等待所有線程運作起來,其代碼如下所示:
主線程代碼:
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); //主線程阻塞等待事件到來
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);
}