2009-07-23 64 views
2

一個我有一個派生兩個線程,然後在下面的Windows代碼等待,直到他們都完成了:是否有並行線程相當於WatiForMultipleObjects

hThreads[0] = _beginthread(&do_a, 0, p_args_a); 
hThreads[1] = _beginthread(&do_b, 0, p_args_b); 
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE); 

我現在移植相同的代碼使用並行線程,但我不知道該如何做WaitForMultipleObjects相當於:

pthread_create(&hThreads[0], 0, &do_a, p_args_a); 
pthread_create(&hThreads[1], 0, &do_b, p_args_b); 
??? 

是否有一個等同的方式,使用並行線程,來實現相同的功能?

回答

4

如果要等到所有,因爲你在這裏做,你可以簡單地調用pthread_join()爲每個線程。它會完成同樣的事情。

pthread_create(&hThreads[0], 0, &do_a, p_args_a); 
pthread_create(&hThreads[1], 0, &do_b, p_args_b); 

pthread_join(hThreads[0], NULL); 
pthread_join(hThreads[1], NULL); 

如果你有更多的線程,你可以看中它並在for循環中執行此操作。

+0

我需要調用了pthread_exit在do_a和do_b? – 2009-07-24 00:15:43

1

我總是隻用一個for循環與在pthread_join

int i; 
for(i=0;i<threads;i++) 
    pthread_join(tids[i], NULL); 
相關問題