1

I have the following situation:

In my C code under Linux I start a number threads in sequence with phtread_create(). Once this is done I invoke pthread_join() in a loop for all of the threads above, in the order in which they were created. Since I don't know when a given thread is going to terminate and join, it might be the case that my code is blocked waiting for the first thread to join, while some of the other threads that were created later have already terminated and are waiting to join.

What I am looking for is something that behaves like pthread_join(), but with the peculiarity that it would stop blocking whenever ANY of the threads created above terminates. Is this at all possible?

Jay Smith
  • 19
  • 4
  • 1
    Does this answer your question? [Non-blocking pthread\_join](https://stackoverflow.com/questions/73468/non-blocking-pthread-join) – Marco Mar 01 '23 at 19:48
  • Thanks. While not exactly what I had in mind it does provide the basic capability to do what I want. – Jay Smith Mar 01 '23 at 23:16
  • I don't think the linked question is a duplicate _per se_. What that question seeks to do (a non-blocking join), and what this one asks to do (block until the any one of _N_ threads terminate) are rather different. – pilcrow Mar 03 '23 at 13:53

2 Answers2

4

You can achieve the same effect by not using pthread_join but instead your own synchronization construct. (For what it's worth, POSIX.1-2017 explicitly regards pthread_join as a convenience, not as a multithreading primitive.)

If you don't need your worker threads' return values, you can simply have a shared counter — protected by a mutex and accompanied by a condition variable — that each (detached) thread decrements and signals when it is "done." Effectively, this is Java's CountDownLatch.

If you do want to collect their return values, have each (detached) worker put its value to a thread-safe queue.

Since you're no longer relying on join, you can run the worker threads as detached.

In either scenario, your waiting thread can do whatever it likes after any decrement or dequeuing.

pilcrow
  • 56,591
  • 13
  • 94
  • 135
-1

Looks like you want to use a function like pthread_tryjoin_np or pthread_timedjoin_np:

The pthread_tryjoin_np() function performs a nonblocking join with the thread thread, returning the exit status of the thread in *retval. If thread has not yet terminated, then instead of blocking, as is done by pthread_join(3), the call returns an error.

It's non-standard though, so your milage may vary.

Marco
  • 7,007
  • 2
  • 19
  • 49