broken mutexing attempt

R

RFPOP3

What is wrong with this code? What I expect from a mutex is that it can
only be locked once. There may be multiple objects pointing to the same
mutex (as there are in the sample code below), but I expect that once a
mutex is locked, no other object, no other process, nothing, should be able
to acquire a lock on that object until the first lock is released.

Instead, I see that both mutexes m1 and m2 are able to claim locks
simultaneously. That's broken, in my opinion, and not at all what I want.
How can I cause two handles to the same mutex to remain mutually
exclusive -- even from within the same thread?

using System;
using System.Threading;

namespace ConsoleApplication356
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
bool createdNew;

//creates a new mutex
Mutex m1 = new Mutex(false, "MyMutex123", out createdNew);
Console.WriteLine("created new = {0}", createdNew);

//creates a second mutex object with a handle to the first object
Mutex m2 = new Mutex(false, "MyMutex123", out createdNew);
Console.WriteLine("created new = {0}", createdNew);

//lock the mutex named "MyMutex123"
Console.WriteLine("Claimed m1 = {0}", m1.WaitOne(10, false));

//this should fail, since "MyMutex123" is already locked, but it
merely
//acquires a second lock! how can i cause this second lock attempt to
fail?
Console.WriteLine("Claimed m2 = {0}", m2.WaitOne(10, false));

//clean up
m2.ReleaseMutex();
m1.ReleaseMutex();
}
}
}
 
J

Joakim Karlsson

The same *thread* can request the same mutex several times. The thread
must release the mutex the same number of times it acquires it.

Regards,
Joakim
 
J

Joakim Karlsson

Instead, I see that both mutexes m1 and m2 are able to claim locks
Think about it. What you are suggesting is that a thread should be able
to dead lock with itself. How would that get resolved? In your code, if
m2.WaitOne() would hang unti m1 was released, nothing would happen
because m1 cannot be released because the m1.ReleaseMutex() statement
will never be reached...


Regards,
Joakim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top