[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 694
  • Last Modified:

Kill child thread (win32 api)


Me here with another API question.

I'm using CreateThread() to make a child thread for a given processes. However, I want to know how to be able to kill this thread by making it enter some cleanup routine, and then die peacefully. Normally this would just be about signalling, but it seems rather complex since I'm dealing with a multithreaded processes. I only want the child to die, and before it ends, it must run a function.

Help appreciaited

1 Solution
When the thread is created, you can pass it a pointer to a parameter.  Make that parameter a pointer to a bool, which when set, tells the thread it's time to go away.  Of course, the thread must regularly check that flag.
Or, just create a global variable that is accessible to all threads, and have the child thread check it every so often.
nerdmikeAuthor Commented:
Won't that create problems though

I'm not too familiar with whats going on under the hood, but isnt it a bad idea to have to threads potentially accessing the same address simulatously?

Every worker thread must have stop event associated with it. When parent thread wants to stop child worker thread, it signals stop event and waits when worker thread actually exits. Worker thread must periodically test it's stop event state, and exit immidiately when this event is signaled. Worker thread must be always responsive and exit quickly when it's stop event signaled.

// parent thread code - start thread
HANDLE hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
HANDLE hThread = CreateThread(...);

// child thread code
while (...)    // some loop
       // do something ...

       // test for stop event
       if ( WaitForSingleObject(hStopEvent, 0) == WAIT_OBJECT_0 )    // request to stop
// clean-up and return

// parent thread code - stop thread
SetEvent(hStopEvent);        // ask thread to stop
WaitForSingleObject(hThread, INFINITE);    // wait when thread actually exits

In real programs I never use INFINITE loop, instead of this I use some maximal timeout (number of seconds) and after this kill worker thread using TerminateThread and report bug (non-responsive worker thread is bug).

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now