Jake
Jake

Reputation: 2907

Confusion on CreateMutex

Let says I call CreateMutex.

HANDLE h;
h=CreateMutex(NULL, TRUE, NULL);
waitforsingleobject(h, INFINITE);
////Random Code
ReleaseMutex(h);

Assuming I have multiple threads running, the first thread to reach the function createmutex essentially blocks all the other threads from the //random code section until release mutex is called right?

Upvotes: 4

Views: 7504

Answers (4)

ds27680
ds27680

Reputation: 1993

Well taking into account that you create an unnamed mutex, each thread will create an unnamed mutex of its own and assume ownership upon creation. Since each thread has its own mutex all threads will be able to run in parallel.

So you should create the mutex once for all threads if you want it to be unnamed. From looking at your code you should also check if mutex creation succeeded.

Then in the function that gets called from multiple threads call WaitForSingleObject on the previously created mutex.

Check the returned result if it returned because you got ownersip of the mutex or the wait terminanted because the mutex was abandoned.

Make sure you call ReleaseMutex on the mutex handle if you got ownersip. Probably you should think of using RAII to manage the mutex for many reasons (to make sure the mutex is properly released when exceptions occur or when a return statement is inserted before the ReleaseMutex to name just a few).

Sometime when the mutex is no longer needed make sure you call CloseHandle on the MutexHandle.

For an example illustrating how to use mutexes see here: "Using Mutex Objects"

For a basic multithreading wrap see here: Using Threads

Upvotes: 1

OJ.
OJ.

Reputation: 29399

Only if the same mutex reference is shared across all threads/processes. You're not sharing it, you're creating it each time. You'll need to name it so that they all get the same mutex for your code to work.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170509

Since you don't specify a name for the mutex each thread will create its own distinct mutex other threads will not be aware of.

A critical section would be a better choice in your scenario.

Upvotes: 1

decltype
decltype

Reputation: 1601

It doesn't, because you have created an unnamed mutex (the third parameter is the name). Assuming the example code is run in multiple threads, each thread will create a new unnamed mutex, and will promptly get access to the critical section (Random Code), because they are only waiting for their own mutex.

To fix this, either let h be a global handle that all threads have access to, and call CreateMutex once outside the shared code, or provide CreateMutex with a name (third argument). In the latter case, subsequent calls to CreateMutex will return a handle to the existing mutex.

Upvotes: 15

Related Questions