Manu Galán
Manu Galán

Reputation: 35

Usage of mutexes in interporcess sync in c

I've been searching for a while and I've decided to ask as I'm unable to find a right answer.

Actually I've got two processes

Process 1:

#include <windows.h>
#include <stdio.h>

// This process creates the mutex object.

int main(void)
{
    HANDLE hMutex; 

    hMutex = CreateMutex( 
        NULL,                        // default security descriptor
        TRUE,                       // mutex owned
        TEXT("AnotherMutex"));  // object name

    if (hMutex == NULL) 
        printf("CreateMutex error: %d\n", GetLastError() ); 
    else 
        if ( GetLastError() == ERROR_ALREADY_EXISTS ) 
            printf("CreateMutex opened an existing mutex\n"); 
        else printf("CreateMutex created a new mutex.\n");

    if(WaitForSingleObject(hMutex, INFINITE) == WAIT_FAILED)
        printf("Error while waiting for the mutex.\n");
    else
        printf("Mutex openned by second process.\n");

    CloseHandle(hMutex);

    return 0;
}

Process 2:

#include <windows.h>
#include <stdio.h>

// This process opens a handle to a mutex created by another process.

int main(void)
{
    HANDLE hMutex; 

    hMutex = OpenMutex( 
        MUTEX_ALL_ACCESS,            // request full access
        FALSE,                       // handle not inheritable
        TEXT("AnotherMutex"));  // object name

    if (hMutex == NULL) 
        printf("OpenMutex error: %d\n", GetLastError() );
    else printf("OpenMutex successfully opened the mutex.\n");

    if(!ReleaseMutex(hMutex)){
        printf("Error while releasing the mutex.\n")
    }

    CloseHandle(hMutex);

    return 0;
}

So when I run the first process it just doesn't wait for the second process to release the mutex but; as the mutex is created owned, nonsignaled, it shouldn't wait till some process/thread releases it and then print the message?

Upvotes: 0

Views: 259

Answers (1)

Eugene
Eugene

Reputation: 2908

It seems that you have confused between two types of synchronization objects: Mutexes and Events.

Mutexes are generally used to protect access to shareable resource. At the entrance to the critical section the WaitForSingleObject on the Mutex should be called. If Mutex is not obtained by another execution unit (thread or process) this execution unit obtains it and continues running, otherwise it is locked until other process releases it. At the end of the critical section the Mutex should be released. See Using Mutexes. That is why your process is not suspended.

Events on the other hand are used to synchronize execution units or to notify something. When one creates an event it specifies its signaled state. When WaitForSingleObject is called and the event is in the non-signaled state the execution unit will be suspended until something signals the event. See Using Events

Bottom line in your case you should use the Event

Upvotes: 1

Related Questions