WenHao
WenHao

Reputation: 1235

Variable scope for lock mechanism

Can someone explain in detail why scope of the variable being lock matter? For example:

lock(variable){ //do something here ! }

In msdn, it states to avoid locking public type and best to lock private or private static type. During the locking, what is actually being lock? The variable address or what?

Upvotes: 1

Views: 366

Answers (3)

Sergii Vashchyshchuk
Sergii Vashchyshchuk

Reputation: 970

lock accepts an instance of type System.Object. All instances of System.Object contain some hidden field in memory which is used for synchronization purposes (lets call it ThreadId). So, what happens when you call lock with some object? The lock statement (actually it is a syntax sugar for Monitor.Enter) checks whether the passed object has something in ThreadId field, and if it doesn't have anything, it puts there some identifier (id of current thread as far as I remember), enters the block of code under the lock statement and in the end of this block - resets the ThreadId value. If the ThreadId field is not empty, it stops and waits until it become empty. In such way it is guaranteed that only one thread can access the code section covered by lock with same passed object.

Why it is not recommended to use public properties/fields in lock? With locks, it is very easy to make a deadlock (when thread A waits for some action from thread B which in its turn waits for action from thread A). So, it is very important to control all locks made on same objects. When you design some class, you know about all private fields, only you can access them and only you can use them in locks. Once the field become public, you lose this control. Yes, you still can control all locks around this field inside your class, but you don't know how this field will be used by consumers of your class, they also can use it for locks and thus cause the deadlock.

Upvotes: 3

AlexD
AlexD

Reputation: 32576

This variable is just some kind of a unique tag. Making it private avoid incidental locking with the same tag somewhere else.

And some comments regarding internal lock implementation can be found here:

http://blogs.msdn.com/b/junfeng/archive/2004/02/18/75454.aspx

Upvotes: 2

TGH
TGH

Reputation: 39268

If you lock on a private member in a particular object you are only locking in that instance. If you lock on a static field you will lock in all instances of the object.

Upvotes: 0

Related Questions