Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I terminate a secondary thread waiting for an object

I created a secondary thread using _beginthreadex. When the process wants to stop. it has to terminate both threads. The issue is the secondary thread is waiting on some handle (using WaitForSingleObject) and the main thread wants to terminate secondary one.

How can main thread notify the second thread to stop with WaitForSingleObject and then terminate?

like image 255
user2731777 Avatar asked Dec 08 '22 13:12

user2731777


1 Answers

Add new event which is used to stop the thread:

HANDLE hStopEvent;
hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

To stop another thread:

SetEvent(hStopEvent);    // ask thread to stop
WaitForSingleObject(hThread, INFINITE);   // wait when thread stops

In the thread code, replace WaitForSingleObject with WaitForMultipleObjects. Wait for exitsting event + hStopEvent. When hStopEvent is signaled, exit the thread function.

HANDLE hEvents[2];
hEvents[0] = <your existing event>;
hEvents[1] = hStopEvent;

for(;;)      // event handling loop
{
    DWORD dw = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);

    if ( dw == WAIT_OBJECT_0 )
    {
         // your current event handling code goes here
         // ...
    }
    else if ( dw == WAIT_OBJECT_0 + 1 )
    {
        // stop event is set, exit the loop and thread function
        break;
    }
}
like image 173
Alex F Avatar answered Dec 28 '22 22:12

Alex F