Hi,
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.

Recommended Answers

All 2 Replies

Go the pthread_cancel()/pthread_cleanup_pop() route. It is the easiest.
And use pthread_setcancelstate() etc. to control cancelability so that you only cancel at known points to make cleanup easier.

pthread_cancel would probably be your best option for cancellation and cleanup, though weigh up whether it is actually worth the effort to terminate the threads or just let them run to completion. Obviously this depends on the nature and size of the data and operations being performed as well as the reason for cancellation.

You also need to consider the actual functions performed by the threads - i.e. have they updated shared-state at a point before they are cancelled? and do you need to roll this change back? This may need to be a part of the cleanup callback.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.