Friday, 13 April 2012

How to terminate thread gracefully

Wait for "terminate" event inside thread callback and once it's signalled, set flag which will cause execution to leave the loop. In the main thread wait for worker thread's handle (join):



Output:
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Terminate Event signalled
Thread terminated

NOTE: Another solution is using InterlockedCompareExchange.

No comments: