Pthreads - Join a thread group, wait for the exit

In the POSIX pthread_join(thread) interface, pthread_join(thread) can be used to block until the specified thread exits.

Is there a similar function that will allow blocking until any child thread exits?

This will be similar to the UNIX wait() system call, except that it applies to child threads, not processes

+4
source share
3 answers

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

Using the pthreads API, you can use pthread_cond_wait and friends to set up a "condition" and wait. When the thread is about to exit, report a status to wake the waiting thread.

Alternatively, another way is to create a pipe with pipe , and when the stream is complete, write to the pipe. On the main thread, expect either select , poll , epoll , or your favorite option at the other end of the pipe. (It also allows you to wait for other FDs at the same time.)

Newer versions of Linux also include "eventfds" to do the same, see man eventfd , but note that this is only recently added. Please note that this is not POSIX, it is only Linux, and it is only available if you are sufficiently updated. (2.6.22 or better.)

I personally always wondered why this API was not designed to handle things like file descriptors. If it were me, they would be "eventables" and you could select files, streams, timers ...

+7
source

I do not think that there is any function in the POSIX thread interface.

You will need to create your own version - for example. an array of flags (one flag per stream) protected by a mutex and a condition variable; where before "pthread_exit ()" each thread receives a mutex, sets its flag, and then "pthread_cond_signal ()". The main thread waits for a signal, then checks the flag array to determine which thread / s needs to join (more than one thread can be attached to it).

+2
source

You need to configure the pthread variable: pthread_cond_wait (), pthread_cond_signal () / pthread_cond_broadcast ().

0
source

Source: https://habr.com/ru/post/1333975/


All Articles