Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WaitForSingleObject not work

Tags:

c++

winapi

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.

like image 416
Tang Khai Phuong Avatar asked Aug 26 '26 07:08

Tang Khai Phuong


1 Answers

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;
 }
like image 104
Logan Capaldo Avatar answered Aug 27 '26 19:08

Logan Capaldo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!