Вопрос

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top