8

I am creating a thread using _beginthreadex function. The function address I am passing in it has an infinite while loop (while(1)) . I have the threadid and threadhandle.

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

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

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

6
  • 7
    You'll have to fix your code, you need to give the thread an exit condition. Run dangerous and uncooperative code in another process if necessary. Mar 25, 2015 at 9:25
  • is this c or c++, windows specific? etc...
    – UmNyobe
    Mar 25, 2015 at 9:25
  • Added winapi tag since this is indeed Windows-specific.
    – Lundin
    Mar 25, 2015 at 9:28
  • @UmNyobe yes it is c,c++ windows.
    – lsrawat
    Mar 25, 2015 at 9:29
  • @Hans that's the last thing I wanna do , so is there any other way possible to do this.
    – lsrawat
    Mar 25, 2015 at 9:30

3 Answers 3

14

You should - literally - never use TerminateThread(). And I'm not even joking. If you are terminating a thread from the outside, all resources reserved in it will be leaked, all state variables accessed inside will have an undetermined state and so on.


The solution for your problem might be signaling your thread to finish itself. It can be done by a volatile variable changed by thread-safe means (see InterlockedIncrement() on that), a Windows event, or something like that. If your thread has a message loop you can even do it by sending a message to ask it to stop.

2
  • Yes I read all this on msdn also. But I thought may be if there is a way to do this (kill thread safely from outside). Actually to modify the while loop that is inside the thread was my last option. But it seems that's the only option.
    – lsrawat
    Mar 25, 2015 at 9:37
  • @Israwat - Believe me, I develop heavily multithreaded applications (servers mostly), and killing a thread from the outside is a really bad practice leading to enormous headache. Also, if you are using a framework like MFC, you will leak a lot of memory, since MFC threads reserve a lot of memory for background MFC objects.
    – mg30rg
    Mar 25, 2015 at 9:40
8

The proper way is to create an event "kill me", by using CreateEvent, then flag this event when you wish to kill the thread. Instead of having your thread wait while(1), have it wait while(WaitForSingleObject(hevent_killme, 0)). And then you can simply let the thread callback finish and return, no need to call _endthreadex or such.

Example of callback function:

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

  return 0;
}

Caller:

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.

13
  • while(1) loop is inside the thread function. I am not waiting for thread too terminate in an infinite while loop .
    – lsrawat
    Mar 25, 2015 at 9:32
  • @lsrawat Yes I understood that, my answer is written with that assumption. I'll clarify the answer a bit.
    – Lundin
    Mar 25, 2015 at 9:34
  • @Israwat - You don't6 have to. Lundin advises you to examine the state of the event, not the thread.
    – mg30rg
    Mar 25, 2015 at 9:34
  • 2
    Use a bool variable, then test it everytime in the while(1) loop...?
    – user1551592
    Mar 25, 2015 at 9:44
  • 1
    @user9000 Good for you. This question is however about the Windows-specific beginthread() function, so your rant isn't relevant. If it makes you happier, I believe the very same code could be written with POSIX functions instead.
    – Lundin
    Mar 25, 2015 at 9:56
7

Instead of while(1), you can use while(continue_running), where continue_running is True when the thread loop should run. When you want to stop the thread, make the controlling thread set continue_running to False. Of course make sure that you properly guard continue_running with mutexes as it is a variable whose value can be modified from two threads.

11
  • 2
    And remember to declare 'continue_running' as volatile, because otherwise optimisation might break your code. (In Visual Studio or gcc, in other IDEs it might differ.)
    – mg30rg
    Mar 25, 2015 at 9:44
  • 1
    @mg30rg on most CPUs, bools are atomic operations
    – user1551592
    Mar 25, 2015 at 9:45
  • 3
    @user9000 - It is not about booleans but compiler optimization. If your compiler isn't avare of the multithreaded nature of your variable it might caches/replicates/multi-instatiates/skips/etc. it for performance reasons.
    – mg30rg
    Mar 25, 2015 at 9:46
  • 2
    Thread-safety for such a variable might not be a concern anyhow, if there is only one thread setting it to a non-zero value, and another thread reading it. volatile to prevent incorrect optimizations is indeed good practice, but I think most compilers don't make such optimization assumption mistakes nowadays?
    – Lundin
    Mar 25, 2015 at 9:48
  • 2
    @mg30rg True, it's always a good idea to take extra caution, you might also want to add that volatile will cause it to always read from memory as this is one of the reasons one would use volatile in a single/multi threaded application.
    – user1551592
    Mar 25, 2015 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.