Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

posix

pthreads

In the POSIX thread interface, 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

like image 932
Mike Avatar asked Jan 02 '11 06:01

Mike


2 Answers

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...

like image 169
Thanatos Avatar answered Nov 09 '22 14:11

Thanatos


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).

like image 2
Brendan Avatar answered Nov 09 '22 13:11

Brendan