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.
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.
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:
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. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With