0

After a reading, I could understand C#'s Lock internally Uses Monitor.Enter and the Monitor.Enter acquires a lock for a critical section by using .Net CLR's Sync block flags.

However, I am interested to understand the logic/tech in acquiring lock when 2 parallel threads are executing to acquire the sync block flag at a same exact time. Considering Acquiring lock is also an operation on top of the user code, How is it possible that the same operation from different threads on a shared resource at a same time can't conflict.

Muthukumar Palaniappan
  • 1,622
  • 5
  • 25
  • 49

1 Answers1

-1

Monitor.Enter Calls methods down the line untill you get to methods implemented inside the CLR, so i don't know exactly how .net does it specifically, however i (mayhaps wrongly) assume that on x86 they do it with a Spinlock

https://en.wikipedia.org/wiki/Spinlock

Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
  • Thanks Ronan for pointing me the X86's way.. I read the spinlock- waits recursively using the registers til the lock is released. However the Wiki doesnt says when 2 threads compete at a same time and executes the same spin lock, how that will be sequenced. So that one thread can acquire it. But one thing I could assume from your answer is, there should be a logic at processor level to sequence the parrallel calls which attempt to grab the flag. – Muthukumar Palaniappan Jun 20 '19 at 05:50
  • @MuthukumarPalaniappan It is guaranteed at the hardware level, the atomic instruction isn't the one that just "uses" the registers but also lookups the (shared by core/proc) memory, the xchg line. This means the actual hardware instruction set guarantees that nothing will happen "during" this instruction that can have an effect on its result. [locked] is the memory address of the variable you would lock(variable) in C#. So while one thread does the exchange, another thread cannot change the value, this means you know if the lock is free or not depending on the value you now have in eax – Ronan Thibaudau Jun 22 '19 at 06:46
  • @MuthukumarPalaniappan don't forget to mark the answer as accepted if it correctly answered your question. – Ronan Thibaudau Nov 28 '19 at 17:17