0

I wasn't able to find this anywhere.

When you use various locking mechanisms in DotNET, how is it implemented under the hood?

The first thread that manages to lock the object gets to use it.

But, how are the others waiting for the lock? I get that they are blocked until they get a lock, but how is it implemented? Is it some kind of while(...) loop? Or is something else going there?

Shocky2
  • 504
  • 6
  • 24
  • 1
    Does this answer your question? https://stackoverflow.com/questions/5111779/lock-monitor-internal-implementation-in-net –  Dec 11 '20 at 16:07
  • @Amy Thank you. Not quite the answer I was hoping for tho, so it doesn't quite answer my question. – Shocky2 Dec 11 '20 at 16:13
  • 3
    Have you read the answers? You are saying that this sentence, `When thread start to contends for a lock with other threads firstly it it does spin-wait loop for a while trying to obtain lock. All this actions performs in user-mode. Then if no success OS kernel object Event creates, thread is switched to the kernel-mode and waits for signal from this Event.` does not answer your question? –  Dec 11 '20 at 16:14
  • Blocking a thread requires the help of the operating system. The CLR uses [WaitForSingleObjectEx](https://github.com/dotnet/runtime/blob/f513349a68a2f0e05189ca2fe2972b1da306995e/src/coreclr/vm/threads.cpp#L432). – Hans Passant Dec 11 '20 at 16:59
  • If you aren't familiar with the win32 api behind the locks, they are made up of Critical Sections, Mutexes, Events, and Semiphores. See [this](https://learn.microsoft.com/en-us/windows/win32/sync/synchronization-functions). Those functions are what we "old school" native win32 programmers still use. Mr. Passant's answer references the function that waits for a handle to be signaled or times out based on what is passed to the function. – Señor CMasMas Dec 11 '20 at 17:40

0 Answers0