mutexes
hey can any explain to me why when i run two programs together that are competing for the mutex that only 1 ever seems to get it? the only time the program2 gains ownership of the mutex is when the program1 is closed??
the code is the same for both programs as i want them both to send a mesage to another program to be displayed.
the code is as follows:-
while(true)
{
WaitForSingleObject(hIMMutex, INFINITE);
cout << "producer 2 has ownership of the mutex" << endl;
strcpy(pSharedVirtualMemoryStartAddress1, "message");
cout << "pulse to the reader that the message is available" <<endl;
PulseEvent(hIMAvailableEvent);
cout << "Wait for the message to be accepted by the reader" << endl;
WaitForSingleObject(hIMAcceptedEvent, INFINITE);
cout << "Relinquish ownership of the mutex" << endl;
ReleaseMutex(hIMMutex);
}
cout << "outside of for loop" << endl;
UnmapViewOfFile(pSharedVirtualMemoryStartAddress1);
CloseHandle(hIMAvailableEvent);
CloseHandle(hIMAcceptedEvent);
CloseHandle(hIMMutex);
CloseHandle(hMappingIn);
cout << "Done" << endl;
}
any help would be much appreciated!
thanks in advance folks
[1370 byte] By [
Scudeto] at [2007-11-11 8:17:16]

# 1 Re: mutexes
I can't tell for sure because I'm more of a POSIX person but check the following: does the
ReleaseMutex(hIMMutex); call ever gets executed? Also, Could it be that the loop is too tight, meaning, it keeps executing so fast, that by the time the mutex has been released, the loop runs once more and acquires the same mutex which has just been released. The other process will always be slower with respect to getting a notification, acquiring the mutex etc. so it simply doesn't have a chance to acquire it. In short, try to insert a pause between the release and the next iteration of the loop, e.g.,
cout << "Relinquish ownership of the mutex" << endl;
ReleaseMutex(hIMMutex);
sleep(100); //sleep for 100 milliseconds
}
Danny at 2007-11-11 21:01:26 >

# 4 Re: mutexes
I'm going to throw out some suggestions you should try...
1. As an experiment, replace the PulseEvent with SetEvent. Does the process waiting on the hIMAvailableEvent object receive the signal?
By the way what type of event is hIMAvailableEvent--auto or manual? Read the msdn docs on PulseEvent to understand the behavior of PulseEvent when dealing with manual v auto events. (Also, you will find that MSFT is not recommending the use of PulseEvent when kernel-mode APC are called.)
2. Check the return values of WaitForSingleObject and ReleaseMutex. Remember these calls must be paired otherwise you may end up in an off by one situation and the mutex is never releases until termination. I'm guessing WaitForSingleObject returns WAIT_ABANDONED in process 2 after you kill process 1.
Cheers,
Mike