简体   繁体   中英

Cannot lock mutex in C

I want to create a lock for writing to a log file. I need to use a mutex, though it seems that my implementation is wrong:

#include <stdio.h>
#include <winsock2.h>

void main() {
    HANDLE lock=CreateMutex (
            NULL,           // default security attributes
            FALSE,          // initial owner
            NULL);          // unnamed mutex
    if (lockMutex == NULL) 
        printf("CreatelockMutex error: %d\n", GetLastError());

    WaitForSingleObject(lock, INFINITE);
    WaitForSingleObject(lock, INFINITE);
    printf("I've PASSED the lock!!");
}

the first 'WaitForSingleObject' should pass, (no one acquired the lock) but the second 'WaitForSingleObject' should stuck the program, but it does't happen.. what am I missing?

CreateMutex creates a 'recursive' mutex, ie the mutex can be acquired repeatedly by the same thread. Another thread would not be able to acquire it. And that makes perfect sense.

If you need to create a non-recursive mutex, use CreateSemaphore instead.

From Microsoft's docs: "The thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its execution."

Try with two threads...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM