What type of locking mechanism uses locks?

Does the C # keyword use "yielding", "spin-locking" or a hybrid approach to resolve conflicts?

So far, my requests in the .net lock expression have not received a response. I will send a message if I find more. So far, I could find When to use spinlock ... with Mecca's well-formulated accepted answer.

But I'm looking for some final answer or documentation regarding .net / C #, if anyone has one.

+6
source share
3 answers

The following code:

lock (_syncRoot) { // Do stuff } 

Translated by the compiler to:

 Monitor.Enter(_syncRoot) try { // Do stuff } finally { Monitor.Exit(_syncRoot); } 

This is a naive (and old) implementation, in fact, with .NET 4.0 the implementation is more or less like this (see Eric's blog for a full link):

 bool locked = false; try { Monitor.Enter(_syncRoot, ref locked); } finally { if (locked) Monitor.Exit(_syncRoot); } 

EDITED

Monitor.Enter() this say how Monitor.Enter() works? Well, the default Mono implementation uses a semaphore to get the lock, but the Microsoft.NET implementation is different.

I was reading concurrent programming on Windows (Joe Duffy), when the paragraph caught my attention, my first answer said: "No, it does not use rotation because performance can be inefficient in general cases." The correct answer is yes, .NET Monitor uses rotation. Both .NET Monitor and critical Windows partitions rotate briefly before returning to the true expectation of a kernel object. This algorithm is called the “two-phase blocking protocol”, and this is necessary because context switches and kernel transitions are very expansive, with a multiprocessor machine rotation can avoid both of them.

Also, do not forget that these are implementation details and can be changed in any version (or the algorithm may differ for different hardware due to the JIT compiler).

+9
source
 lock (obj) { } 

was just syntactic sugar for Monitor . Enter in try ... finally.

 Monitor.Enter(obj); try { } finally { Monitor.Exit(obj); } 

Now this is kind of a little better (thanks to Mark and Adriano for supporting me).

 bool locked = false; try { Monitor.Enter(_syncRoot, ref locked); } finally { if (locked) Monitor.Exit(_syncRoot); } 
+1
source

This is Microsoft documentation saying lock () wraps Monitor.Enter / Exit

"use the C # lock statement, which wraps the Enter and Exit methods in try ... finally block."

from http://msdn.microsoft.com/en-us/library/de0542zz.aspx

If you need a spinlock type, you can use ReaderWriterLockSlim ()

http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx

0
source

Source: https://habr.com/ru/post/919846/


All Articles