Click here to Skip to main content
15,879,490 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How can I kill a thread while it is waiting on semaphore or message queue?

AFAIU kill or terminate functions aren't safe.

Thanks!
Posted
Comments
KingsGambit 8-Jul-10 0:16am    
Reason for my vote of 5
Good question.

1 solution

Correct, terminating another thread without giving it a chance to cleanup is generally not a good thing; instead if you want a thread to die you should work out some kind of cooperative notification method so that the thread knows that it should return from its execution method, thereby ending the thread cleanly.

If the thread is blocked on a semaphore, one way would be to create another event and instead of simply waiting for the semaphore do a wait multiple objects on both the shutdown event and semaphore. Other threads can signal the target thread to exit by setting the shutdown event in which case the target thread knows that its time to cleanup its resources and exit.

Another method would be to use a simple flag value instead of a full blown event. Then change the semaphore acquisition calls to use a timeout value. If the method times out then you can check the flag and either continue waiting if it's not set or cleanup and exit if it is.

Yet another solution would be to not call blocking methods if you know that they're going to block. Then it's just a matter of polling the "thread exit" flag as before while you wait for the blocking condition to become unblocked.
 
Share this answer
 
Comments
KingsGambit 8-Jul-10 0:14am    
Reason for my vote of 1
Correctly explains different ways to deal with blocked threads
KingsGambit 8-Jul-10 0:15am    
Reason for my vote of 5
Correctly explains different ways to deal with blocked threads

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900