Discussion:
Mutex Problem
(too old to reply)
unknown
2007-07-21 19:54:01 UTC
Permalink
Hi All,

I have 2 applications that I need to synchronize their mutual access of some
shared memory, and for this reason each of these applications tries to create
an unowned named-mutex upon its startup:

hMutex = CreateMutex (NULL, false, szMutexName);

From this moment and on, any of them gets hold of the mutex before accessing
the shared memory, and releases it immediately afterwards:

if (WAIT_OBJECT_0 != WaitForSingleObject (hMutex, 1000))
{
return (-1);
}

<access the shared memory>...

ReleaseMutex (hMutex);

NOTE: NONE of the applications call CloseHandle (hMutex)!

To be more accurate, one of them acts as a master (that is, makes both
read/write operations), and the other as a slave (that is, may only read the
shared memory).

Now, everything works fine all along, no matter what's the first application
to run (and create the mutex), and what's the second.

BUT when the slave ends running and closes, the master application only
partially succeeds getting hold of the mutex (that is, sometimes it get hold
of the mutex, sometimes not, in a seemingly repeating way), and therefore
cannot properly funtion.

1) Why is it so, and how can I solve it?

2) Should the slave application close the mutex somehow upon closing?

3) Should I use OpnetMutex() instead of CreateMutex()?

Thanks for your help,
Ofer.
Kalle Olavi Niemitalo
2007-07-21 20:57:43 UTC
Permalink
Post by unknown
if (WAIT_OBJECT_0 != WaitForSingleObject (hMutex, 1000))
{
return (-1);
}
You should really check for WAIT_ABANDONED too.
Otherwise a process can acquire the mutex without realizing it,
and then lock others out.
unknown
2007-07-22 08:36:02 UTC
Permalink
Hi Kalle,

Thanks for your answer.

Instead, calling CloseHandle() before leaving solved the problem, though I
really can't fully understand that.

Sincerely,
Ofer.
Ben Voigt [C++ MVP]
2007-08-20 13:41:48 UTC
Permalink
Post by unknown
Hi Kalle,
Thanks for your answer.
Instead, calling CloseHandle() before leaving solved the problem, though I
really can't fully understand that.
You still need to check for WAIT_ABANDONED, in case the other app was
forcibly closed (TerminateProcess) while holding the mutex.
Post by unknown
Sincerely,
Ofer.
Loading...