Share via


How is lock keyword of C# implemented?

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

From:
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…

Thanks

Comments

  • Anonymous
    February 18, 2004
    The comment has been removed
  • Anonymous
    February 25, 2004
    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 :D

    http://www.blogcn.com/user8/flier_lu/main.asp?id=1256525
  • Anonymous
    April 26, 2004
    How can I use the lock statement to suspend all threads, when entering a critical code section?