Question 6
Back to Exercise
Why can two threads each doing ++counter 1000 times on a plain int end with fewer than 2000?
- A ++ is slow
- B It is a read, an add and a write; the steps of two threads can interleave and lose updates (and it is undefined behaviour) Correct
- C ints overflow
- D Threads share no memory
Correct Answer: Option B
Use std::atomic<int> or a mutex.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!