LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 1

A thread modifying a copy versus a reference Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 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 <functional>
#include <iostream>
#include <thread>

void add_ten(int x) { x += 10; }
void add_ten_ref(int& x) { x += 10; }

int main() {
    int a = 1, b = 1;
    std::thread t1(add_ten, a);
    std::thread t2(add_ten_ref, std::ref(b));
    t1.join();
    t2.join();
    std::cout << a << ' ' << b << '\n';
    return 0;
}
  • A 1 11 Correct
  • B 11 11
  • C 1 1
  • D 11 1
Correct Answer: Option A

Thread arguments are copied; only std::ref passes the real variable.

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