2015-08-28 52 views
0

我有以下代碼來同步多個線程。在下面的代碼中,創建16個線程,看起來只有1個等待成功; 4保持着wa;; 11不需要等待(因爲標誌已被設置爲1)。它是如何工作的? pthread_cond_signal()和pthread_cond_wait()

請問您可以看看問題出在哪裏?謝謝!

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 !!! 
+0

「void * run_thread(** viod ** * ptr)」?請複製實際的代碼! – Olaf

回答

4

你叫pthread_cond_signal,這是唯一保證喚醒一個線程。你想pthread_cond_broadcast,這是保證喚醒所有等待的線程。

相關問題