When a thread tries to enter a critical section and obtain a lock, what is it actually doing?
I’m asking this because I usually create an object (of type object) which will serve for locking purposes only.
Consider the following: I want to write a method which accepts a collection, and an object which will serve as the locking object so the whole collection manipulation inside that method will be declared inside the critical section which will be locked by that given object.
Should I pass that locking object using “ref” or is passing a reference copy of that object is enough? In other words – since the lock statement is used with reference types only, does the mechanism check the value of the referenced object, or does it check the pointer‘s value? because obviously, when passing an object without “ref”, I actually get a copy of the reference, and not the reference itself.
Here’s a typical pattern that you can follow for locking. Basically, you can create a locking object that is used to lock access to your critical section (which, as @Hans said, is not protecting the object that you’re working on — it just handles the lock).
This example was from Joseph Albahari’s online book on threading. It provides an excellent overview of what’s going on when you create a
lockstatement and some tips/tricks on how to best optimize for it. Definitely highly recommended reading.Per Albahari, again, the
lockstatement translates in .NET 4 as:It’s actually safer than a straight
Monitor.Enterand then callingMonitor.Exitin yourfinally, which is why it was added in .NET 4.