Cancel POSIX stream after doing shared work

There are several threads working on a task. Once the thread is successful, the entire thread must be canceled since the work is done. How can I cancel other threads as soon as one thread completes successfully? Who will call pthread_cancel ()and how does a successful thread report mainor the thread that generated it (return value?).

UPDATE

I do not want to just call exit, because now I want to get some control. For example, after the threads are canceled, I will process the result on a successful thread and, possibly, do some additional processing, or just want the process to work for some additional work.

+5
source share
2 answers

You can choose a simple scheme where main does everything.

Have mainrun all the threads and execute downon some kind of semaphore. When the thread completes the task, do upon this semaphore. When main is unlocked, it can pthread_cancelexecute all threads (and then pthread_jointo make sure).

This method mainstarts and stops all threads, so it should be fairly simple.

+4
source

One easy way is to invoke exit(), which terminates the process along with all threads. It can be called from any thread.

Another way is to create your main thread and wait for worker threads, and as soon as one of the worker threads completes:

+1

All Articles