Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel POSIX thread after a common work is done

There are multiple threads working on a task. Once a thread succeeds all of the thread should be canceled, as the work is accomplished. How can i cancel the other threads once one thread has terminated successfully ? Who will call pthread_cancel () and how will the successful thread tell main or the thread which spawned it (return value ?).

UPDATE

I do not want to simply call exit as i want now some control. For example after the threads are canceled , i will process the found result by the successful thread and possible do some more processing, or simply want to keep the process running for some more work.

like image 603
phoxis Avatar asked Aug 19 '11 17:08

phoxis


2 Answers

You could choose a simple scheme where main does everything.

Have main start all the threads and do a down on some semaphore. When a thread finishes the task, do an up on that semaphore. When main is unlocked it can pthread_cancel all the threads (and then pthread_join to make sure).

This way main starts and stops all the threads so it should be pretty simple.

like image 58
cnicutar Avatar answered Sep 20 '22 05:09

cnicutar


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

Another way is to have your main thread spawn and wait on the worker threads, and once one of the worker threads has completed either:

  • tell nicely the other threads to terminate and wait till they do, or
  • abruptly pthread_cancel() them. By default threads are created with PTHREAD_CANCEL_DEFERRED, which means they won't terminate until they call any of the cancellation point functions, see Thread Cancellation for a good description. So, if you threads are doing some long computations you might want to set their cancellation state to PTHREAD_CANCEL_ASYNCHRONOUS to terminate the thread immediately, see pthread_setcanceltype.
like image 33
Maxim Egorushkin Avatar answered Sep 23 '22 05:09

Maxim Egorushkin