1

I have a multi-threaded program, which each thread runs in a loop if a variable exit_requested = 0. Once SIGINT is received by the main thread, the SIGINT handler makes exit_requested = 1. Each thread then exits the loop, and the main thread then calls pthread_cancel() on each child thread. Is it necessary to then call pthread_join() on the child threads?

Rachid K.
  • 4,490
  • 3
  • 11
  • 30
doctopus
  • 5,349
  • 8
  • 53
  • 105
  • 1
    The function `pthread_cancel` only sends a cancellation **request**. There is no guarantee that the thread will have finished execution by the time the function returns. Therefore, if your main thread returns from the function `main` without calling `pthread_join` beforehand, you will be killing all remaining threads. Depending on what the threads are doing at the time they get killed, this can lead to data loss and is usually not recommended. – Andreas Wenzel Oct 23 '20 at 23:43
  • 1
    Taking it one step further, you have a voluntary cleanup mechanism (`exit_requested`) which is being totally bypassed by using `pthread_cancel`. Use one or the other, but not both. Or at least give the thread a chance to notice and honour `exit_requested` before calling `pthread_cancel`. – ikegami Oct 24 '20 at 00:11
  • Ahh i see, so if i use `exit_requested`, it's better to just `pthread_join()`? – doctopus Oct 24 '20 at 00:19
  • @doctopus: Yes, that is what I would recommend. – Andreas Wenzel Oct 24 '20 at 01:14

0 Answers0