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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With