LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 4

fetch_add returns the previous value Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <atomic>
#include <iostream>

int main() {
    std::atomic<int> n{10};
    int a = n.fetch_add(5);         // returns the OLD value
    int b = ++n;                    // returns the NEW value
    int c = n.exchange(100);        // sets 100, returns the old value
    int expected = 100;
    bool swapped = n.compare_exchange_strong(expected, 7);
    std::cout << a << ' ' << b << ' ' << c << ' ' << swapped << ' ' << n << '\n';
    return 0;
}
  • A 10 16 16 1 7 Correct
  • B 15 16 16 1 7
  • C 10 16 100 1 7
  • D 10 16 16 0 100
Correct Answer: Option A

fetch_add returns the value before adding; prefix ++ the value after. compare_exchange succeeds because n equals expected (100).

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