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.