开发者

Why are locks performed on separate objects? [duplicate]

This question already has answers here: Closed 13 years ago.

Possible Duplicate:

Difference between lock(locker) 开发者_JAVA技巧and lock(variable_which_I_am_using)

In all of the "thread-safe" code examples i've seen, they lock on a separate dummy object. Why cant locks be directly performed on the data in question?


Locking on a separate private dummy object gives you a guarantee that no one else is locking in that object.

If you lock on the data and that same piece of data is visible to the outside you lose that guarantee. For example:

public class MyObject
{
    public void SharedMethod()
    {
        lock (this)
        {
            // Do stuff
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyObject o = new MyObject();

        lock (o)
        {
            new Thread(() =>
            {
                // Gets blocked 2s because of external lock
                o.SharedMethod();
            }).Start();

            Thread.Sleep(2000);
        }
    }
}


Jeff Richter (author of CLR Via C#) explains why in this article on Safe Thread Synchronization.

Specifically, in that article the section "Why the Great Idea isn't So Great" answers your question.

It's actually a chapter from the book CLR Via C#.

In summary, having a private object as the "synclock" object allows your class to encapsulate and control any locking your class needs. Therefore regardless of how many clients use your class, locking is performed consistently and correctly.


There's some great stuff on this on Eric Gunnerson's blog. See here and here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜