Sobes.tech
Middle

What will happen if two threads simultaneously add values to a variable without synchronization primitives? What could be the results?

sobes.tech AI

Answer from AI

When two threads simultaneously increment a shared variable without using synchronization primitives (such as lock, mutex), a race condition occurs. This means that read and write operations can overlap, leading to incorrect results.

For example, if the variable is 0, and two threads simultaneously perform x = x + 1, both might read 0, add 1, and write back 1, whereas the correct result should be 2.

The outcomes can be:

  • Lost updates (increment not counted).
  • Unpredictable variable value.

To prevent this, synchronization should be used, for example:

int x = 0;
object locker = new object();

void Increment() {
    lock(locker) {
        x = x + 1;
    }
}

Or use atomic operations from System.Threading.Interlocked.