Terminating a thread gracefully not using TerminateThread()

后端 未结 4 1846
不思量自难忘°
不思量自难忘° 2020-12-05 12:12

My application creates a thread and that runs in the background all the time. I can only terminate the thread manually, not from within the thread callback function. At the

4条回答
  •  没有蜡笔的小新
    2020-12-05 12:50

    Since you don't know what the thread is doing, there is no way to safely terminate the thread from outside.

    Why do you think you cannot terminate it from within?

    You can create an event prior to starting the thread and pass that event's handle to the thread. You call SetEvent() on that event from the main thread to signal the thread to stop and then WaitForSingleObject on the thread handle to wait for the thread to actually have finished. Within the threads loop, you call WaitForSingleObject() on the event, specifying a timeout of 0 (zero), so that the call returns immediately even if the event is not set. If that call returns WAIT_TIMEOUT, the event is not set, if it returns WAIT_OBJECT_0, it is set. In the latter case you return from the thread function.

    I presume your thread isn't just burning CPU cycles in an endless loop, but does some waiting, maybe through calling Sleep(). If so, you can do the sleeping in WaitForSingleObject instead, by passing a timeout to it.

提交回复
热议问题