1

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!

Community
  • 1
  • 1
Anish Ramaswamy
  • 2,326
  • 3
  • 32
  • 63

1 Answers1

1

Some searching, I found these:

Community
  • 1
  • 1
masoud
  • 55,379
  • 16
  • 141
  • 208
  • I had downvoted by mistake. I was wondering if there was a way to do this without using exception handling. Also, your second link and the link I posted are the same. Looking into the first link now. Thanks! – Anish Ramaswamy Mar 09 '13 at 07:02
  • I didn't notice your second link. But the first link maybe help you. – masoud Mar 09 '13 at 07:04
  • Your first link seems to be useful. Will definitely try that out. But my question was whether all this is actually necessary. I just want that thread to exit on some event. Is exception-handling the best way to do that? – Anish Ramaswamy Mar 09 '13 at 07:08
  • If you want avoid using [`TerminateThread`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717%28v=vs.85%29.aspx) you should build a handy way yourself. Such as exceptions, or just a global flag between threads. – masoud Mar 09 '13 at 07:13