Monitor (lock)

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm having a tough time understanding the concept of locking "on an object".

If a monitor is used to protect a critial section, then what does any object
reference have to do with it? Does this allow different instances of the
same object to, in fact, run the same critical section and assume they're
accessing instance varaibles only?

What would be a scenario where some method in class A would lock on an
instance of class B?

If you're locking to protect global (static) data structures, then you lock
on typeof(this), right? Well... what does that mean? You've locked on an
instance of the Type class, so no other instance can run that critical
section?

I guess I just don't understand why you need the object reference. This
also leaves me a little confused on the SyncRoot property of may collections.
Is locking on 'this' not good enough? Do I actually have to lock on the
underlying data structure to assure thread safety.

Thanks,

Andrew
 
Andrew said:
I'm having a tough time understanding the concept of locking "on an object".

If a monitor is used to protect a critial section, then what does any object
reference have to do with it? Does this allow different instances of the
same object to, in fact, run the same critical section and assume they're
accessing instance varaibles only?

What would be a scenario where some method in class A would lock on an
instance of class B?

The object the reference refers to is basically irrelevant. It was a
mistake, IMO, to have monitors on all objects rather than having
Monitor instances created purely for the sake of locking.
If you're locking to protect global (static) data structures, then you lock
on typeof(this), right?

No. For one thing that wouldn't compile. For another, it's as bad as
lock (this) in terms of keeping the lock private. See
http://www.pobox.com/~skeet/csharp/threads/lockchoice.shtml
Well... what does that mean? You've locked on an
instance of the Type class, so no other instance can run that critical
section?

It means that nothing else can acquire the lock to that Type instance's
monitor while you've got it.
I guess I just don't understand why you need the object reference. This
also leaves me a little confused on the SyncRoot property of may collections.
Is locking on 'this' not good enough? Do I actually have to lock on the
underlying data structure to assure thread safety.

I think it's better to lock on something else entirely, myself...
 
Back
Top