Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully shutdown a thread in C

Tags:

c

winapi

I have something like this:

DWORD WINAPI test(LPVOID lpParam) {
    while (1) {
        /*DO STUFF*/
    }
}

int main() {
    ...
    hThread = CreateThread(NULL,0,test,NULL,0,&dwThreadId);
    ...
}

How can i shutdown the Thread without TerminateThread()? My first idea was creating a global variable (shouldshutdown = 0/1), set it in the main() when the Thread should shutdown. Then call ExitThread() in the Thread. Therefore i have to check for this variable in the while loop of the thread which is bad style i guess.

like image 290
Kntlii Avatar asked May 05 '16 10:05

Kntlii


1 Answers

You an event that the thread can check to see if it needs to stop. For example (without error handling):

DWORD WINAPI test(LPVOID lpParam) 
{
    HANDLE hEvent = (HANDLE)lpParam

    while (WaitForSingleObject(hEvent, 0) == WAIT_TIMEOUT) 
    {
        /*DO STUFF*/
    }
}

int main() {
    hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)
    hThread = CreateThread(NULL,0,test,(LPVOID)hEvent,0,&dwThreadId);
    // Do
    // Stuff
    // Tell the thread to exit
    SetEvent(hEvent)

    // Wait for the thread to exit
    WaitForSingleObject(hThread, INFINITE);
}

The general pattern is to give the thread some sort of alertable object that it can monitor and something else can set. In this case I've used a manual reset event. The while loop checks to see if the event has been signaled, and if not it does stuff. When it is signaled then WaitForSingleObject will return WAIT_OBJECT_0 and the loop will exit and you'll fall out of the thread function.

In the main function all you need to do after signalling the event is wait for the thread to exit.

like image 152
Sean Avatar answered Oct 08 '22 23:10

Sean