通常的方法(在并行线程,至少)是:
- 您有几个
pthread_t
引用到正在运行的线程。
- 而不是最后你的
while
循环,你等待所有的线程完成类似于pthread_join(threadX, NULL);
的东西。
在你的情况,我看不出有任何的API来获取线程,但一旦你运行(也许要求以某种方式sc
)螺纹保持,代码是相似的。
编辑:
如果你只是想等待一个条件,很容易与条件变量。假设你已经使用这些:
pthread_mutex_t end_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
bool all_threads_done = false; // Signals that all the threads are finalized
然后,在你main()
就可以等着它:
pthread_mutex_lock(&end_mutex);
while (!all_threads_done)
pthread_cond_wait(&condition_var, &end_mutex);
的wait
将释放互斥锁在等待。然后,每个线程上,您必须具备以下条件:
// Do whatever the thread has to do...
// ...
// and then, at the end...
pthread_mutex_lock(&end_mutex);
if (no_more_threads()) // You have to figure this thing out to ensure no more threads
all_threads_done = true;
pthread_cond_signal(&condition_var);
pthread_mutex_unlock(&end_mutex);
注意,最后,即使当你在做一个while
,它不是一个忙等待,因为大部分的时间在主线程正在等待pthread_cond_wait
,并在任何线程结束时被唤醒。
你正在使用什么线程库?并行线程? –
是的,我使用pthreads,但main()不知道pthread_t引用 – JACKSONMEISTER