开发者

Synchronising access to an object that multiple threads can access

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.


The code as presented is wrong. Locking on a local variable (myLock) 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜