Sobes.tech
Junior — Middle

Can you list the main synchronization primitives provided by the standard library?

sobes.tech AI

Answer from AI

The following primary synchronization primitives are available in the C# standard library (in the System.Threading namespace):

  • lock (Monitor) — provides exclusive access to a resource by locking a code section.
  • Mutex — a cross-process mutex used for synchronization between processes.
  • Semaphore and SemaphoreSlim — limit the number of threads that can access a resource simultaneously.
  • AutoResetEvent and ManualResetEvent — events for signaling between threads.
  • ReaderWriterLockSlim — allows multiple threads to read a resource simultaneously but blocks writing.
  • SpinLock — a lightweight primitive for short locks without context switching.

Example of using lock:

private readonly object _lockObj = new object();

void CriticalSection()
{
    lock(_lockObj)
    {
        // code that should be executed by only one thread at a time
    }
}