views:

78

answers:

2

Can anyone explain why this works:

    Object ready_lock = new Object();
    Object thread_lock = new Object();
    public static bool able_to_get_lock = false;

    public void GetThreadLock()
    {
        if (Monitor.TryEnter(thread_lock,2))
        {
            able_to_get_lock = true;
        }
    }

    [TestMethod]
    public void ThreadingModelTest()
    {
        Monitor.Enter(ready_lock);
        Thread t1 = new Thread(new ThreadStart(GetThreadLock));
        t1.Start();
        Thread.Sleep(400);
        Assert.IsTrue(able_to_get_lock);

    }

but if I change the object types of the locking objects to a String (as below) it fails:

    String ready_lock = "Hello";
    String thread_lock = "Hello";

It's been confusing me for a while now. Thanks :)

+14  A: 

When you set them both to "Hello", you end up with both variables having the same value, due to string interning. It's like doing

Object ready_lock = new Object();
Object thread_lock = ready_lock;

So basically it's a case of "if you've got two locks involved, they can be independently locked by different threads, but with only one lock, only one thread can acquire the lock at a time."

Jon Skeet
Ahhhhhhhhhhhhhh... Thankyou.
Richard
+5  A: 

It is kind of optimization, similar const string are treated as the same object, just change you code:

String ready_lock = "1)Hello";
String thread_lock = "2)Hello";
Dewfy
Cheers Dewfy, very helpful answer as well.
Richard