How to safely close a THREAD that has an infinite loop

I create a stream using the _beginthreadex function. In the address of the function I'm passing, it has an infinite while ( while(1) ) while(1) . I have threadid and threadhandle .

I can use TerminateThread(threadhandle,1); But it is dangerous.

A safe way is to kill the stream using _endthreadex , but it can only be used inside the stream, and I wanted to kill the stream from the outside.

So please suggest if there is a safe way to close, end, or kill a thread safely from the outside using threadid or threadhandle .

+6
source share
3 answers

You should - literally - never use TerminateThread (). And I'm not even joking. If you terminate the stream from outside, all resources reserved in it will leak out, all state variables that are accessed inside will have an undefined state, etc.


A solution to your problem may signal that your thread is terminating. This can be done by a mutable variable modified by thread-safe means (see InterlockedIncrement ()), a Windows event or something like that. If your thread has a message loop, you can even do this by sending a message to ask it to stop.

+12
source

The right way is to create a β€œkill me” event using CreateEvent, and then mark this event when you want to kill the stream. Instead of waiting for the while(1) stream, wait [t21>. And then you can just enable the thread callback and return, no need to call _endthreadex or such.

Example callback function:

 static DWORD WINAPI thread_callback (LPVOID param) { ... while(WaitForSingleObject(hevent_killme, 0) != WAIT_OBJECT_0) { // do stuff } return 0; } 

Subscriber:

 HANDLE hevent_killme = CreateEvent(...); ... void killthread (void) { SetEvent(hevent_killme); WaitForSingleObject(hthread_the_thread, INFINITE); CloseHandle(hevent_killme); CloseHandle(hthread_the_thread); } 

Never use TerminateThread.

+8
source

Instead of while(1) you can use while(continue_running) , where continue_running is True when the thread loop should be executed. If you want to stop the thread, set the continue_running control chain to False . Of course, make sure you protect continue_running mutexes correctly, as this is a variable whose value can be changed from two threads.

+7
source

Source: https://habr.com/ru/post/984228/


All Articles