Junior — Middle
Can you explain the concept of interlocked and its application in multithreaded programming?
sobes.tech AI
Answer from AI
Interlocked is a set of atomic operations in C# that provide safe modification of shared data in a multithreaded environment without using heavy locks.
The main interlocked operations include:
- Increment/Decrement — atomic increase or decrease of a value.
- CompareExchange — compare and swap if the value is equal to the expected.
- Exchange — replace the value with a new one.
Using interlocked helps avoid race conditions when updating variables, such as counters or flags, ensuring correctness and performance.
Example of usage:
int counter = 0;
// Atomic increment of the counter
Interlocked.Increment(ref counter);
// Atomic compare and swap
int original = Interlocked.CompareExchange(ref counter, 10, 5);
Thus, interlocked is a low-level tool for safe working with shared data in multithreaded programming.