Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 955
Jake Avatar asked Dec 03 '22 09:12

Jake


2 Answers

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.

like image 98
decltype Avatar answered Dec 28 '22 19:12

decltype


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.

like image 37
sharptooth Avatar answered Dec 28 '22 19:12

sharptooth