2014-03-28 97 views
0

所以我想要有3個線程都增加一個全局整數。我認爲,當一個線程被創建,它是一個fork的simulair,那個main會繼續在新創建的線程的同一時間執行代碼。然而,這並不是什麼,因爲第二和第三個線程在第一個線程完成之後從不創建。線程同時運行

void * say_it(void *) 
{ 
    int count = 0; 

    while(BUFFER < 24) 
    { 

     //LOCK 
     if (pthread_mutex_lock(&output_lock) != 0) 
    { 
     perror("Could not lock output: "); 
     exit(-1); 
    } 

     //print message 
     cout << "TID: " << pthread_self() << " PID: " << "WORK IN PROGRESS " << "Buffer: " << BUFFER << endl; 
     BUFFER++; 

     //UNLOCK 
     if (pthread_mutex_unlock(&output_lock) != 0) 
    { 
     perror("Could not unlock output: "); 
     exit(-1); 
    } 
     count++; 
    } 

    //print final message 
    cout << "TID: " << pthread_self() << " worked on the buffer " << count << " times" << endl; 

} 

int main(int argc, char *argv[]) 
{ 

    int num_threads = 3; 
    pthread_t *thread_ids; 
    void *p_status; 

    //Use unbuffered output on stdout 
    setvbuf(stdout, (char *) NULL, _IONBF, 0); 

    //Set up an output lock so that threads wait their turn to speak. 
    if (pthread_mutex_init(&output_lock, NULL)!=0) 
    { 
     perror("Could not create mutex for output: "); 
     return 1; 
    } 

    //Create 3 THREADS 
    thread_ids = new pthread_t[num_threads]; 

    // generate threads 
    for (int i = 0; i < num_threads; i++) 
    { 

     int *arg = new int; 
     *arg = i; 
     if(pthread_create(&thread_ids[i],NULL,say_it,NULL) > 0) 
     { 
     perror("creating thread:"); 
     return 2; 
     } 

     if (pthread_join(thread_ids[i], &p_status) != 0) 
     { 
     perror("trouble joining thread: "); 
     return 3; 
     } 
    } 




    return 0; 
} 

我也嘗試在節目的區域放置睡眠(1),但沒有成功。

任何人都可以解釋這一點嗎? 謝謝!

+2

'pthread_join'等待線程完成。所以你不會創建第二個線程,直到第一個線程與主線程「加入」爲止。 – Anthony

+0

這是一個複製粘貼錯誤:你'「加入」'代碼調用'pthread_create',和你的創作循環不斷調用'pthread_join'。 – dasblinkenlight

回答

1

當您撥打pthread_join時,main將阻塞,直到該線程完成。在線程上調用pthread_join之前,您需要創建所有線程。

備註:您在// join threads and print their return values的評論後再次撥打pthread_create。這一切都需要刪除。

1

在循環中,您創建一個線程,然後與它聯接,因此在第一個線程完成之前您不會創建下一個線程。這裏沒有併發性。

的10第二個循環看起來完全錯誤的,因爲你只分配空間3個線程ID,但在這裏要創建10個線程。

+0

對不起,我的意思是我貼在此之前刪除最後一個線程(累我猜:/)。我剛剛編輯了這個以消除 – user3444975

0

您正在創建線程並等待線程完成。將連接代碼移出for循環,如下所示。

for (int i = 0; i < num_threads; i++) 
    { 

     int *arg = new int; 
     *arg = i; 
     if(pthread_create(&thread_ids[i],NULL,say_it,NULL) > 0) 
     { 
     perror("creating thread:"); 
     return 2; 
     } 

    } 
    for (int i = 0; i < num_threads; i++) 
    { 

     if (pthread_join(thread_ids[i], &p_status) != 0) 
     { 
     perror("trouble joining thread: "); 
     return 3; 
     } 
    } 
+0

什麼是'arg'呢? – pat

+0

我們要問的問題的創造者,可能是他想將它傳遞給線程函數。 – user207064