LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 8

thread_local gives each thread its own variable Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 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 <iostream>
#include <thread>
#include <vector>

thread_local int calls = 0;      // one per thread
int count_call() { return ++calls; }

int main() {
    std::vector<int> last(3);
    std::vector<std::thread> pool;
    for (int t = 0; t < 3; ++t)
        pool.emplace_back([&last, t] {
            int r = 0;
            for (int i = 0; i <= t; ++i) r = count_call();     // thread t calls t+1 times
            last[t] = r;
        });
    for (auto& th : pool) th.join();
    count_call();
    std::cout << last[0] << last[1] << last[2] << ' ' << calls << '\n';
    return 0;
}
  • A 123 1 Correct
  • B 136 7
  • C 123 7
  • D 111 1
Correct Answer: Option A

Each thread starts with its own calls = 0. The main thread's copy was touched only once.

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