Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why should we avoid lock(this)? [duplicate]

Possible Duplicate:
Why is lock(this) {…} bad?

In C# to make a critical region thread safe we can use lock() statement. The lock statement takes an object. What is wrong if we pass this to the lock statement?

like image 626
Unmesh Kondolikar Avatar asked Sep 17 '10 17:09

Unmesh Kondolikar


People also ask

Why do we need locks?

Locks are used to guard a shared data variable, like the account balance shown here. If all accesses to a data variable are guarded (surrounded by a synchronized block) by the same lock object, then those accesses will be guaranteed to be atomic — uninterrupted by other threads.

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 are locks needed in a multi threaded program?

A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.

Can two threads acquire the same lock?

Typically, threads cannot acquire locks twice in a row: a thread must release an acquired lock before attempting to acquire it again. However, reentrant locks can be acquired multiple times by the same thread. Reentrant locks allow code to acquire a lock before calling other functions that acquire the same lock.


2 Answers

Because this is not encapsulated by the class and thus it is hard to reason about who locks on this. I.e. in order to find out what part of the code is locking on this you need to go through a lot. If, on the other hand, you restrict locking to a private member, it is easy to reason about where locking takes place.

like image 68
Brian Rasmussen Avatar answered Sep 19 '22 04:09

Brian Rasmussen


From http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx:

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:

  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

like image 45
cleek Avatar answered Sep 21 '22 04:09

cleek