I have a program, which has some worker threads that are performing tasks. The main thread assigns work to the worker threads. The worker threads wait for a message from the main thread (with data) and start to work. After completion of work, working threads again wait for more work. The usual scenario.
Now I want to cancel some work that a worker thread W is doing based on input main thread receives. The main thread is M. I have considered about 3 possibilities.
1. Kill W from M. Simple but it is undesirable for two facts:
i. I have to create another thread for the killed one.
ii. I cant clean up memory.
2. Put 'checkpoints' in the 'Work' function for the working threads to check for a flag and stop work if flag is set. This is also undesirable because the function calls more functions and the total code is huge. Can clean up memory here.
3. Use pthread_cancel with a cleanup function pushed with pthread_cleanup_push. I haven't used pthread_cancel, but I am thinking with what I read. It seems I can kill the thread and cleanup here. But still I lose the thread and have to create a new one.
I am wondering what to do. Can anyone help please? Thank you.