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();
}
}
}
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();
}
}
}