1
我想建立一個程序,其中pthreads等待來自先前pthread的信號運行,並在完成時發出下一個pthread信號。使pthread等待另一個數據
例如,假設我有4個pthreads。 #1先運行。我希望#2在開始執行之前等待#1完成,當它完成時,它將發信號#3。 #3等待#2,並最終發出信號#4。 #4完成後簡單終止。
我該如何做到這一點?
我想建立一個程序,其中pthreads等待來自先前pthread的信號運行,並在完成時發出下一個pthread信號。使pthread等待另一個數據
例如,假設我有4個pthreads。 #1先運行。我希望#2在開始執行之前等待#1完成,當它完成時,它將發信號#3。 #3等待#2,並最終發出信號#4。 #4完成後簡單終止。
我該如何做到這一點?
對於這個問題,您不需要條件變量或互斥鎖。 pthread_join()
就足夠了。
將前一個線程的線程標識傳遞給其後繼線程。允許繼任者撥打pthread_join()
,等待其前任完成。
main()
只需要在最後一個線程上pthread_join()
。
但是,正如註釋中指出的那樣,在單線程中可以更高效地實現功能。
C中的解決方案可能是這個樣子:
static void
wait_for_thread(pthread_t *t)
{
if (t) {
pthread_join(*t, 0);
printf("Thread %zu finished...\n", t - threads);
}
}
static void *
thread_fun(void *arg)
{
wait_for_thread(arg);
/* ... */
return 0;
}
int main()
{
int i;
for (i = 0; i < 4; ++i) {
pthread_create(&threads[i], 0, thread_fun, i ? &threads[i-1] : 0);
}
wait_for_thread(&threads[3]);
return 0;
}
C++中的解決方案可能是這個樣子:
int main()
{
std::array<std::thread, 4> threads;
auto wait_for_thread = [&threads](int p) {
if (p >= 0) {
threads[p].join();
std::cout << "Thread " << p << " finished...\n";
}
};
auto thread_fun = [&wait_for_thread](int p) {
wait_for_thread(p);
//...
};
for (auto &t : threads) {
t = std::thread(thread_fun, &t-&threads[0]-1);
}
wait_for_thread(3);
}
聽起來像是你要麼需要一個互斥體或條件變量。 – Holly
這不是C ... – Eregrith
建議1 - 不要多用一個線程。 –