[英]C - Waiting For Multiple Threads to Terminate
我試圖等待所有線程在main()進程終止之前終止。 這是我到目前為止的內容:
void* mapperFunction()
{
printf("Hello\n");
return NULL;
}
int main()
{
int i; // Used in "for" loops.
int N = 3;
pthread_t* mapperThreads = (pthread_t*) malloc(sizeof(pthread_t) * N);
for ( i = 0; i < N; i++)
{ // Creates all the mapper threads.
pthread_create( &mapperThreads[N], NULL, mapperFunction, NULL);
}
for ( i = 0; i < N; i++)
{ // Waits for all the mapper threads to terminate.
pthread_join( mapperThreads[N],NULL);
}
return 0;
}
運行此代碼時,我得到三個不同的輸出。
1-您好\\ n
2- Helle \\ n您好\\ n
3-您好\\ n您好\\ n您好\\ n
看起來main()進程並不總是等待所有線程終止。 我究竟做錯了什么?
在每種情況下,您都希望使用&mapperThreads[i]
而不是&mapperThreads[N]
。
也許您正在尋找pthread_barrier_wait
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.