Click to See Complete Forum and Search --> : A question regarding waitforsingleobject


dullboy
July 31st, 2005, 11:17 AM
After I create a thread using _beginthread, then I call waitforsingleobject to wait for thread handle until thread function returns. But it looks like the function waitforsingleobject hangs in there. I have to set an event at the end of thread function and then call waitforsingleobject to wait for the event handle instead. Why? Thanks for your inputs.

kuphryn
August 1st, 2005, 01:21 PM
Correct. Thread handle is important for when you want to refer to that thread in some API, but without locking mechanisms.

Kuphryn

dullboy
August 1st, 2005, 09:06 PM
Thanks for your reply. However, if you check msdn regarding waitforsingleobject, you will find out the following information,

The WaitForSingleObject function can wait for the following objects:

Change notification
Console input
Event
Job
Mutex
Process
Semaphore
Thread
Waitable timer

See, indeed WaitForSingleObject may wait for thread. Any comments are welcome!

Correct. Thread handle is important for when you want to refer to that thread in some API, but without locking mechanisms.

Kuphryn

Hacker2
August 2nd, 2005, 12:34 AM
I think WaitForSingleObject can wait for a thread to terminate,
but not wait for it to start existing.

I mean, once you create it, it exists, yes?

So you have WFSO waiting for something that already happened,
so it just waits forever.

This is why you need to have some sort of event that fires in the thread
and then wait for that event in the main routine

kuphryn
August 2nd, 2005, 12:11 PM
MSDN is dense, but not make everything in MSDN a good or right solution.

Kuphryn

Arjay
August 2nd, 2005, 08:10 PM
Thanks for your reply. However, if you check msdn regarding waitforsingleobject, you will find out the following information,

The WaitForSingleObject function can wait for the following objects:

Change notification
Console input
Event
Job
Mutex
Process
Semaphore
Thread
Waitable timer

See, indeed WaitForSingleObject may wait for thread. Any comments are welcome!Yes WFSO can wait on all those objects - you decide how you need to wait. You can wait either on the thread handle or an event, it depends on when you want to quit waiting. Sometimes, you spin up a thread, do a little work and wait for it to finish. Other times, you spin up the thread, and wait for it to fire an event. It's your choice. One thing to note, is that you probably don't want to use WFSO in a UI thread, but use MsgWaitForMultipleObjects instead.

Arjay