Sobes.tech
Junior — Middle

What methods are used to resolve conflicts when multiple threads access the same object simultaneously?

sobes.tech AI

Answer from AI

In a multithreaded environment, various synchronization methods are used to prevent conflicts when accessing the same object:

  • lock (monitor) — the lock keyword in C# allows you to acquire a block of code so that only one thread can execute it at a time.

  • Mutex — an object that can be used for synchronization between threads and even between processes.

  • Semaphore and SemaphoreSlim — allow limiting the number of threads that can access a resource simultaneously.

  • Monitor — a more flexible mechanism based on lock, with the ability to wait and notify threads.

  • Interlocked — a class for atomic operations on variables (e.g., increment, decrement), preventing race conditions without locks.

  • ReaderWriterLockSlim — allows multiple threads to read data simultaneously but blocks writing while reading is in progress.

Example of using lock:

private readonly object _syncObj = new object();
private int _counter = 0;

public void Increment()
{
    lock (_syncObj)
    {
        _counter++;
    }
}