2016-11-06 105 views
1

我想了解多線程如何工作。我已經寫了下面的代碼 `併發多線程

void handler(void *arg) 
{ 
    printf("Printf from cleanup handler: %s\n", (char*)arg); 
} 

void print(const char *msg) 
{ 
    printf("%7s: Pid=%d Tid:%lu\n", msg, getpid(), pthread_self()); 
} 

void* thread_function1(void *args) 
{ 
    printf("Received: %d\n", (int)args); 
    print("Thread"); 
    pthread_cleanup_push(handler, "hello"); 
    pthread_cleanup_pop(1); 
    printf("Thread Done\n");  
    return (void *) 0; 
} 

int main(void) 
{ 
    pthread_t tid1, tid2; 
    void *tret; 
    if(pthread_create(&tid1, NULL, thread_function1, (void *)1)) 
     exit(1); 
    if(pthread_create(&tid2, NULL, thread_function1, (void *)2)) 
     exit(1); 
// pthread_join(tid2, &tret); 
// pthread_join(tid1, &tret); 
} 

這段代碼的問題是,主要完成其執行之前thread_function1能夠完成它的執行。如果兩個註釋都被刪除,那麼thread 2僅在thread 1已經完成其執行後才被執行。

我想要做的是有thread 1thread 2同時執行和main應該等待兩個線程完成。

+2

線程做了一個(非平凡的)工作量嗎?難道是'thread_function1'在第二個線程被創建之前完成? –

+0

@WanderNauta我已經更新了這個問題。請看看它。 – Ibrahim

回答

5

該代碼的問題在於,在thread_function1可以完成其執行之前,主要完成其執行。

這是因爲當主線程退出時,進程死亡,包括所有線程。您可以改爲從主線程調用pthread_exit(0),以便其餘線程繼續執行並退出主線程。

如果兩個註釋都被刪除,那麼線程2只有在線程1完成其執行後才被執行。

這不是真的。即tid1tid2在它們被創建後同時執行(「同時執行」取決於你的硬件,調度策略等 - 但就你的程序而言,它們可以被認爲是同時執行的)。 pthread_join()不控制線程執行的順序。它僅影響主線程等待完成線程的順序,即主線程等待tid2先完成,然後等待tid1(如果您沒有註釋那兩行)。

+0

我得到的輸出爲「Received:1 \ n Printf from cleanup handler:hello \ n Received:2 \ n Printf from cleanup handler:hello」 這意味着線程2僅在線程1完成後才執行。我錯過了什麼嗎? – Ibrahim

+0

訂單不固定。嘗試重複執行它幾次,你可能會首先看到「收到2」,然後「收到1」。 – usr

+0

非常感謝。我試過多次運行它,它的工作原理與您所提到的完全相同。謝謝 ! :) – Ibrahim