Reputation: 15197
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 :)
Upvotes: 11
Views: 165
Reputation: 23614
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";
Upvotes: 5
Reputation: 1499770
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."
Upvotes: 14