[英]pthread_join() for asynchronous threads
我寫了一個簡單的演示程序,以便我可以理解pthread_join()
函數。
我知道如何使用pthread_condition_wait()
函數來允許異步線程,但我試圖了解如何使用pthread_join()
函數完成類似的工作。
在下面的程序中,我將Thread 1s ID 傳遞給Thread 2s函數。 在Thread 2s函數中,我調用pthread_join()
函數並傳入Thread 1s ID。 我希望這會導致線程 1先運行,然后線程 2再運行,但我得到的是它們同時運行。
這是因為一次只有一個線程可以使用pthread_join()
函數,並且當我從主線程調用它時我已經在使用pthread_join()
函數了嗎?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *functionCount1();
void *functionCount2(void*);
int main()
{
/*
How to Compile
gcc -c foo
gcc -pthread -o foo foo.o
*/
printf("\n\n");
int rc;
pthread_t thread1, thread2;
/* Create two thread --I took out error checking for clarity*/
pthread_create( &thread1, NULL, &functionCount1, NULL)
pthread_create( &thread2, NULL, &functionCount2, &thread1)
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("\n\n");
exit(0);
}
void *functionCount1()
{
printf("\nFunction 1");
sleep(5);
printf("\nFunction 1");
return(NULL);
}
void *functionCount2(void* argument)
{
pthread_t* threadID = (pthread_t*) argument;
pthread_join(*threadID, NULL);
printf("\nFunction 2");
sleep(5);
printf("\nFunction 2");
return(NULL);
}
輸出:
當使用pthread_create()
創建線程時,兩個線程同時開始執行,並且它們的執行順序沒有固定的順序。 順序取決於操作系統調度和可用處理器的數量等。無論如何,這無法確定,無論如何這就是線程的重點。
當您調用pthread_join()
時會發生什么,調用者等待加入的線程終止。 所以主線程等待thread1
終止,然后等待thread2
。 但是當 main 等待thread1
, thread2
可能已經完成執行並已經終止。 在這種情況下, pthread_join(thread2, NULL);
會立即返回。
你的代碼有一個更大的問題。 您將thread1
的 ID 傳遞給thread2
。 但是如果thread1
在thread2
開始之前完成執行,那么您將使用無效的線程標識符,從而導致未定義的行為。 另一個問題是您的主線程和thread2
都試圖與thread1
。 簡而言之, pthread_join()
不是多線程之間同步的正確工具。 正如您所說,您為此目的使用條件變量/互斥鎖。
我建議,您從thread2
刪除pthread_join()
以修復未定義的行為,如果您想要串行執行線程,那么您必須一個接一個地創建線程並讓它們等待前一個線程終止( pthread_join()
)。 但是這樣做的實際用途很少。 或者讓線程在做任何事情之前等待一個條件變量,你可以使用條件變量讓線程按照你想要的順序進行通信。
您調用未定義的行為。 手冊頁: http : //man7.org/linux/man-pages/man3/pthread_join.3.html
Joining with a thread that has previously been joined results in undefined behavior.
此外,第一個線程可能會在第二個線程之前完成執行。 如果你想要這樣的東西,最好使用pthread_cond_wait()
。
從pthread_join 手冊頁(強調我的):
如果多個線程同時嘗試加入同一個線程,結果是不確定的。 如果調用 pthread_join() 的線程被取消,則目標線程將保持可連接(即不會分離)。
似乎您正是在這種情況下,主線程和線程 2 都試圖pthread_join
線程 1。
您應該為每個線程明確定義一個負責其管理的“所有者線程”。 責任鏈應該形成一個層次的線程樹(即沒有循環或多個父級)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.