开发者

pthreads - Join on group of threads, wait for one to exit

In the POSIX thread inte开发者_运维问答rface, pthread_join(thread) can be used to block until the specified thread exits.

Is there a similar function that will allow execution to block until any child thread exits?

This would be similar to the wait() UNIX system call, except be applicable for child threads, not a processes


I don't think this is directly possible from pthreads per se, but you can work around it fairly easily.

Using the pthreads API, you can use pthread_cond_wait and friends to set up a "condition" and wait on it. When a thread is about to exit, signal the condition to wakeup the waiting thread.

Alternatively, another method is to create a pipe with pipe, and when a thread is going to exit, write to the pipe. Have the main thread waiting on the other end of the pipe with either select, poll, epoll, or your favorite variant thereof. (This also allows you to wait simultaneously on other FDs.)

Newer versions of Linux also include "eventfds" for doing the same thing, see man eventfd, but note this is only recently added. Note that is isn't POSIX, it's Linux-only, and it's only available if you're reasonably up-to-date. (2.6.22 or better.)

I've personally always wondered why this API wasn't designed to treat these things similar to file descriptors. If it were me, they'd be "eventables", and you could select files, threads, timers...


I don't think there's any function in the POSIX thread interface to do this.

You'd need to create your own version of it - e.g. an array of flags (one flag per thread) protected by a mutex and a condition variable; where just before "pthread_exit()" each thread acquires the mutex, sets its flag, then does "pthread_cond_signal()". The main thread waits for the signal, then checks the array of flags to determine which thread/s to join (there may be more than one thread to join by then).


You need to implement a customize one by pthread conditional variable: pthread_cond_wait(), pthread_cond_signal()/pthread_cond_broadcast().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜