Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are locks performed on separate objects? [duplicate]

Possible Duplicate:
Difference between lock(locker) 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?

like image 403
RCIX Avatar asked Dec 09 '09 11:12

RCIX


People also ask

Why do we use lock statement in C?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

Why should you avoid the lock keyword?

Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.

Is lock thread safe C#?

The lock statement is one of the simplest and most common tools for C# developers writing multithreaded applications. It can be used to synchronize access to blocks of code, achieving thread safety by allowing only one thread at a time to execute the code in that block.


3 Answers

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);
        }
    }
}
like image 194
João Angelo Avatar answered Oct 05 '22 08:10

João Angelo


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.

like image 28
Ash Avatar answered Oct 05 '22 09:10

Ash


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

like image 45
RichardOD Avatar answered Oct 05 '22 10:10

RichardOD