Algorithm of lock (obj) { ...} statement in C#

  • Thread starter Thread starter Hyun-jik Bae
  • Start date Start date
H

Hyun-jik Bae

What is the algorithm of lock(obj) { ... }?

The statement above roughly makes me guess that the lock/unlock algorithm in
CLR is inefficient because it adds a critical section for each CLR object
instance.

Am I right? Please reply. Thanks in advance.

Hyun-jik Bae
 
Hyun-jik Bae said:
What is the algorithm of lock(obj) { ... }?

The statement above roughly makes me guess that the lock/unlock
algorithm in CLR is inefficient because it adds a critical section
for each CLR object instance.

Am I right? Please reply. Thanks in advance.

No, you're not.

The C# lock state is a shortcut for a pattern using the
System.Threading.Monitor object.

lock(this)
{
statement(s)
}

is identical to

Monitor.Enter(this);
try
{
statement(s)
}

finally
{
Monitor.Exit(this);
}

Under the covers, Monitor uses a pool of kernel synchronization objects and
attaches them to objects as needed. There are only as many low-level
synchronization objects in use as there are active monitors at any given
time.

-cd
 
Back
Top