Please see the code below:
#include <windows.h>
int main(int argc, char* argv[])
{
HANDLE _mutex = ::CreateMutex(NULL, FALSE, "abc");
if (!_mutex)
throw std::runtime_error("CreateMutex failed");
if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");
printf("Must lock here\n");
if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");
printf("Why come here????\n");
return 0;
}
I don't know why console print out:
Must lock here
Why come here???
Does mutex not work? I want the result only show
Must lock here
And blocking after print the text above.
If you want a synchronization primitive that behaves like you've described you can use an auto-reset event instead.
#include <windows.h>
#include <stdexcept>
#include <stdio.h>
int main(int argc, char* argv[])
{
HANDLE _mutex = ::CreateEvent(NULL, FALSE, TRUE, NULL);
// auto reset // initially signalled
if (!_mutex)
throw std::runtime_error("CreateEvent failed");
if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");
// unsignalled now
printf("Must lock here\n");
// will block forever until someone calls SetEvent
if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");
printf("Why come here????\n");
return 0;
}
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