How is lock keyword of C# implemented?

This question is asked in an internal discussion. And here is the answer from CLR team.

Subject: RE: How is lock keyword of C# implemented?

At the core, it’s typically one „lock cmpxchg“ instruction (for x86) for entry, and one for exit, plus a couple dozen other instructions, all in user mode. The lock prefix is replaced with a nop on uniprocessor machines.

The “lock cmpxchg” instruction basically stores the locking thread’s id in the object header, so another thread that tries to lock the same object can see that it’s already locked.

The actual implementation is a lot more complicated, of course – we use the object header for other purposes, for example, so this must be detected and dealt with, plus when a thread leaves the lock, we must detect whether other threads are waiting and so on…


Comments (5)

  1. .. says:

    This just in, after extensive research it has been discovered there is no Scotch Mist in the CLR.

  2. Flier Lu says:

    Like JVM, every reference type instance in CLR has a pair of Object & ObjHeader object. ObjHeader hold a SyncBlock object which implement the "lock object" behavior, just like the critical section implementation in Win32.

    If you can read Chinese, you could read more detail from my BLog 😀

  3. Jamesy says:

    How can I use the lock statement to suspend all threads, when entering a critical code section?