我怎么能等待任何/所有的pthreads才能完成? [英] How can I wait for any/all pthreads to complete?
问题描述
我只希望我的主线程等待任何和我所有的(P)线程退出之前完成。
I just want my main thread to wait for any and all my (p)threads to complete before exiting.
中的线程来来去去很多不同的原因,我真的不想让他们都跟踪 - 我只是想知道,当他们都走了。
The threads come and go a lot for different reasons, and I really don't want to keep track of all of them - I just want to know when they're all gone.
wait()的这是否为子进程的时候,有没有孩子离开返回ECHILD,但等待不(出现一起工作)(P)的线程。
wait() does this for child processes, returning ECHILD when there are no children left, however wait does not (appear to work with) (p)threads.
我真的不想去通过保持每一个优秀的线程列表的麻烦(因为他们来来去去),则不必调用在pthread_join每个
I really don't want to go through the trouble of keeping a list of every single outstanding thread (as they come and go), then having to call pthread_join on each.
由于有一个快速和肮脏的方式做到这一点?
As there a quick-and-dirty way to do this?
推荐答案
的正确方法是跟踪所有pthread_id的的,但你问一个快速和肮脏的方式,以便在这儿呢。基本上是:
The proper way is to keep track of all of your pthread_id's, but you asked for a quick and dirty way so here it is. Basically:
- 只是保持运行的线程的总数,
- 之前调用pthread_create的, 在主循环加一
- 递减的线程数,因为每个线程结束。
- 然后睡在主过程结束,直到将返回到0。
- just keep a total count of running threads,
- increment it in the main loop before calling pthread_create,
- decrement the thread count as each thread finishes.
- Then sleep at the end of the main process until the count returns to 0.
volatile int running_threads = 0;
pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
void * threadStart()
{
// do the thread work
pthread_mutex_lock(&running_mutex);
running_threads--;
pthread_mutex_unlock(&running_mutex);
}
int main()
{
for (i = 0; i < num_threads;i++)
{
pthread_mutex_lock(&running_mutex);
running_threads++;
pthread_mutex_unlock(&running_mutex);
// launch thread
}
while (running_threads > 0)
{
sleep(1);
}
}
这篇关于我怎么能等待任何/所有的pthreads才能完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!