Sobes.tech
Junior — Middle

How do systems handle the situation when multiple threads access a shared variable or state simultaneously?

sobes.tech AI

Answer from AI

When multiple threads access a shared variable or state simultaneously, a race condition occurs. To prevent incorrect data and ensure correctness, synchronization mechanisms are used:

  • Locks (lock, mutex) — allow one thread to exclusively own a resource, while others wait.
  • Monitors (Monitor.Enter/Exit in C#) — a more flexible locking mechanism.
  • The lock keyword in C# — simplified syntax for monitors.
  • Atomic operations (Interlocked) — for simple operations without full locking.
  • Concurrent collections — thread-safe data structures.

Example using lock in C#:

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

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

This approach guarantees that only one thread modifies the variable at a time.

How do systems handle the situation when multiple… - sobes.tech