I am writing a multithreaded program and i have this question:
Suppose that, while executing in the main thread, i want to terminate all
child-threads. I can’t just send them a termination signal cause i want them
to free dynamically allocated memory first. Can i define a specific signal handler
function in each thread function that is executed, which in turn is going to call
a cleanup function that i will write to do so? If not how can i accomplish my goal??
Thanks,
Nikos
Look at the man page for
pthread_cancel:So you can use
pthread_cancelfrom your main, provided you have registered you cleanup handlers correctly using the above functions.(Do read that man page completely though, it has a lot of important information.)
Edit: (from comments) If you plan on using
PTHREAD_CANCEL_DEFERREDand need to insert a cancellation point somewhere in your code, then usepthread_testcancel. This function checks if a cancellation was requested. If that is the case, the cancellation is serviced (i.e. that call never returns). Otherwise it has no effect.