C++ MFC

Moderators: Lundin
Number of threads: 3337
Number of posts: 9005

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
How to know if a thread is finished and wait for it if it isn't Posted by DeptofMeteors on 26 Mar 2011 at 3:57 PM
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 and 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 without a race condition?
Report
Re: How to know if a thread is finished and wait for it if it isn't Posted by AsmGuru62 on 27 Mar 2011 at 4:19 AM
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:
DWORD WINAPI ThreadCode (PVOID lparam)
{
	// your code here...

	::SetEvent (...); // or ::PostMessage();
	return 0;
}



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.