Re: how does system determine when to enter the thread function when using mutex
"Daniel" <newsonly@cableone.net> wrote in message
news:eqVdWBV7IHA.2336@TK2MSFTNGP03.phx.gbl
Following is a sample code I got from the MSDN help on using the
mutex with multiple threads. I can't figure out how the operating
system decides when the break out of the thread function to allow
entry for another thread.
I don't understand the question. What do you mean, break out of the
thread function? The whole point of threads is that they run
simultaneously, in parallel. The system doesn't need to "break out" of
one to let the other run. The goal of synchronization primitives like
mutexes is to _restrict_ this parallelism (which is sometimes
necessary), not to enable it.
A thread does WaitForSingleObject(ghMutex, INFINITE). Suppose the mutex
is unowned at the moment. In this case, the thread acquires (becomes the
owner of) the mutex, WaitForSingleObject returns, and the thread
proceeds with its work.
Meanwhile, another thread calls WaitForSingleObject on the same mutex.
This time the mutex is owned, so the thread is waiting for it to become
free. WaitForSingleObject simply doesn't return until it happens.
Eventually, first thread calls ReleaseMutex. The mutex is now unowned
again, but there's a thread waiting on it. This thread now acquires the
mutex, its WaitForSingleObject call finally returns, and it proceeds
with its work.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925