Search code examples
c++windowsthread-synchronization

have a running thread exit immediately when a particular event is signaled


Consider the following thread function:

UINT MyClass::threadFunc(LPVOID lParam)
{
    // 1. Initialize stuff
    // 2. Validate stuff
    // 3. Do first task
    // 4. Do second task
    // 5. Un-initialize everything and return
}

This thread is created by a dialog in my application. This thread will run only once in the dialog's lifetime (it is a worker thread).

On the occurrence of some asynchronous event (maybe the click of a button, some other event being signaled, whatever), I want to notify this thread to return immediately so that my dialog can exit gracefully (after waiting for this thread to terminate). I cannot just exit the dialog because this thread will still be running.

I am relatively new to C++ and this is what I had thought of (pseudocode):

  1. Surround the thread function in a try-catch.
  2. On occurrence of that asynchronous event, throw a thread terminate exception.

This didn't work so I researched a bit and found answers similar to this one. But for some reason, I have a feeling that there is a much easier way to accomplish this. I just wanted some clarification before I go about implementing said idea.

Thanks!


Solution

  • Some searching, I found these: