Search code examples
multithreadingpthreadspthread-join

How to join with whichever thread finishes first?


The main thread spawns > 1 threads, and each of them can call return with an error value. If this happens, it is meaningless for the other threads to continue, and so they should be canceled.

So, I want my main thread to:

  • Join with whichever thread finishes first;
  • Check if this thread returned error, and if so, cancel all other threads.

However, pthread_join requires me to specify which thread I want to join with. If I call, for example, pthread_join(thread1, thread1_ret), and thread2 finishes with error, then I won’t be able to know that thread2 finished on error before thread1 finishes, and the fact that thread2 finished prematurely might very well mean that thread1 is currently waiting on a conditional variable that will never be signaled, because only thread2 may signal that variable… So, bad.

I want my main thread to cancel thread1 if thread2 finishes and vice-versa.

How to accomplish this?


Solution

  • How to accomplish this?

    You need a separate communication channel.

    A typical solution involves a queue (of finished threads) and a condition variable.

    The thread that finishes with error puts itself into the queue and signals the condition before returning. The main thread waits on the condition, checks the queue, and joins the thread that it finds there, then cancels all the other threads.

    Note also that async thread cancellation is tricky to get right. It is usually better to have a global variable that all the threads check periodically: while (!exit_requested) { do_work(); }