How to know if a thread is finished and wait for it if it isn't

I can't believe I don't know this already, but I'm unable to figure out how to know if a thread is finished [italic]and[/italic] wait for it if it isn't w/out a race condition. I've used the AfxBeginThread() to start it, and I'm told that I would WaitForSingleObject() to know when it is done, but it seems that that function returns WAIT_FAILED if the thread is no longer running. What's the appropriate way to just know if it's done and wait if it hasn't [italic]without[/italic] a race condition?

Comments

  • [color=Blue]WaitForSingleObject will block the waiting thread until working thread finishes. The return code you got may be due to a very fast working thread - you call Wait... at the time when thread is ALREADY DONE! If your main thread (or the one which starts the working thread) must be running and not waiting - then WaitForSingleObject is not the way to use in this case. There are a couple of ways to let know that thread is done: use SetEvent function or post a custom message if you have HWND to post it to. These things are done at the end of the thread code:[/color]
    [code]
    DWORD WINAPI ThreadCode (PVOID lparam)
    {
    [color=Green]// your code here...[/color]

    ::SetEvent (...); [color=Green]// or ::PostMessage();[/color]
    return 0;
    }
    [/code]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion