Junior — Middle
Kuidas süsteemid käsitlevad olukorda, kui mitu niiti pöörduvad samaaegselt ühise muutujaga või olekuga?
sobes.tech AI
Vastus AI-lt
When multiple threads simultaneously access a shared variable or state, a race condition occurs. To prevent incorrect data and ensure correctness, synchronization mechanisms are used:
- Locks (lock, mutex) — allow one thread to exclusively own the resource, others wait.
- Monitors (Monitor.Enter/Exit in C#) — more flexible locking mechanism.
- The
lockkeyword 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.