LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading MCQ · Question 6

Why is ++counter unsafe across threads? Answer, explanation & discussion

  • MCQ
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links