Cannot lock mutex in C

885 views Asked by At

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?

2

There are 2 answers

0
nullptr On BEST ANSWER

CreateMutex creates a 'recursive' mutex, i.e. 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.

0
Guy Sirton On

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...