Woodstock Blog

a tech blog for general algorithmic interview questions

[Design] Multithreading Async Increment Problem

Question

link

If two threads are incrementing a variable 100 times each without synchronization, what would be the possible min and maximum value.

Solution

Well, max is init+200, and min is init+2. Suggested by the top answer:

  1. P1 & P2 copy var
  2. P1 increments 99 times. so var becomes var + 99
  3. P2 increments once. so var becomes var + 1
  4. P1 copies var (value is var + 1)
  5. P2 increments 99 times. so var becomes var + 100
  6. P1 increments once. so var becomes var + 2