2016-09-30 31 views
0

我正在研究線程和併發編程。嘗試從類中提供的基本示例:無法理解此基本線程行爲

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 

#define NUM_THREADS 8 

void *printGoGators(void *noArg) 
{ 
    printf("Go Gators!\n"); 
    return NULL; 
} 

int main(int argc, char *argv[]) 
{ 
    pthread_t threads[NUM_THREADS]; 
    int rc, t; 
    for (t = 0; t < NUM_THREADS; t++) 
    { 
     printf("Creating thread %d\n", t); 
     rc = pthread_create(&threads[t], 
       NULL, 
       printGoGators, 
       NULL); 
     if(rc) 
    { 
     printf("ERROR %d", rc); 
     exit(-1); 
    } 
    } 
    pthread_exit(NULL); 
} 

此代碼會生成以下輸出。 :

Creating thread 0 
Creating thread 1 
Go Gators! 
Creating thread 2 
Go Gators! 
Creating thread 3 
Go Gators! 
Creating thread 4 
Go Gators! 
Creating thread 5 
Go Gators! 
Creating thread 6 
Go Gators! 
Creating thread 7 
Go Gators! 
Go Gators! 

爲什麼Go Gators!沒有直接與其對應的Creating thread #所有線程後打印? 請幫忙!

+2

因爲你的線程是相互獨立的並且來自創建它們的主線程。因此,一旦啓動,您無法控制首先打印哪個線程。 – HazemGomaa

+0

所以這個問題被認爲是過於寬泛的計算器。我沒有看到有人提供不同的答案。 –

+1

真的很難理解你的問題。你問爲什麼不發生任何理由,你爲什麼不應該發生。你正在看到你應該期待的行爲。如果你有其他期望,請說出爲什麼我們可以在你的推理中解釋錯誤。 –

回答

4

如果你的代碼看起來像這樣,那麼輸出將是你所期望的順序:

for (t = 0; t < NUM_THREADS; t++) 
    { 
     printf("Creating thread %d\n", t); 
     printGoGators(NULL); 
    } 

所以,你正在做的線程會以相同的順序,他們正在創建執行的假設。但是,這種假設是不正確的 - 線程可能以任何順序執行。

1

創建線程後,由操作系統決定執行線程的順序。你可以使用互斥鎖和條件來控制它,以鎖定一個線程讓另一個線程運行,然後解鎖它。

與接受的答案不同,此示例使用線程而不是僅在循環中打印某些內容。

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 

#define NUM_THREADS 8 

pthread_mutex_t myMutex;    // Declere global mutex 
pthread_cond_t myCondition;    // Declere global condition 


void *printGoGators(void *arg) {   

    printf("Go Gators! %i\n", *(int*)arg); 
    delete (int*) arg; 

    pthread_cond_signal(&myCondition); // Signal that a condition is met 

    return NULL; 
} 

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

    pthread_mutex_init(&myMutex, NULL);    // Initialize mutex 
    pthread_cond_init (&myCondition, NULL);   // Initialize condition 

    pthread_t threads[NUM_THREADS]; 
    int rc, t; 
    for (t = 0; t < NUM_THREADS; t++) { 

     int* n = new int; 
     *n = t; 

     printf("Creating thread %d\n", t); 
     rc = pthread_create(&threads[t], 
       NULL, 
       printGoGators, 
       n);    

     if(rc) { 
     printf("ERROR %d", rc); 
     exit(-1); 
    } 


    pthread_cond_wait(&myCondition, &myMutex);   // waite for condition 

    } 
    pthread_exit(NULL); 
} 

結果:

Creating thread 0 
Go Gators! 0 
Creating thread 1 
Go Gators! 1 
Creating thread 2 
Go Gators! 2 
Creating thread 3 
Go Gators! 3 
Creating thread 4 
Go Gators! 4 
Creating thread 5 
Go Gators! 5 
Creating thread 6 
Go Gators! 6 
Creating thread 7 
Go Gators! 7 

主線程創建循環:創建一個線程,然後等待狀態。

新線程:打印消息,然後表示符合條件。

這樣你管理執行的順序。