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...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…