views:

155

answers:

1

My question is partially inspired by this article written by Eric Lippert:
http://blogs.msdn.com/ericlippert/archive/2009/10/19/what-is-this-thing-you-call-thread-safe.aspx

Using Eric's example of a Queue class being accessed by multiple threads. If I have two distinct pieces of code that access the queue:

class MyThreadTest {
    private static Object myThreadLock = new Object();

void MyDequeue() {
    Object myLock = new Object();
    lock (myLock) {
        if (!queue.IsEmpty()) { queue.DeQueue(); }       
    }
}

Object MyPeek() {
    lock (myThreadLock) {
        if (!queue.IsEmpty()) { return queue.Peek(); }
    }
}    

}

Will two threads accessing MyDequeue() at approximately the same time respect the lock, and one gain the lock before the other? Or will the two threads each have different lock objects since they were declared in local scope? If the latter, will declaring the myLock object as a static member fix this issue?

Will two threads, one accessing MyDequeue and the other accessing MyPeek, respect the static myThreadLock, if myThreadLock were in use in MyDequeue instead of the local myLock?

There's a lot I'm unsure about, but I'm wondering if the lock locks a section of code, or if the lock locks the object so that all pieces of code using that lock are 'opened' and 'closed' as one.

If there are any other subtleties in the code above, please point them out as I really am very naive about this process.

+2  A: 

The code as presented is wrong. Locking on a local variable is always useless.

DeQueue() needs to use myThreadLock too, and yes, that means it is competing for access with Peek(). And it should, all actions on the queue should use the same object to lock on.

Henk Holterman
I was fairly sure the DeQueue() method was incorrect and I thought I was somewhat clear in expressing why I thought it was wrong. It's good to know that one lock should be used per 'object' that requires synchronization, so thank you.
Josh Smeaton
Josh, I was aware of that, but I think answers should be very clear and direct.
Henk Holterman