LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 20

joinable() after join, detach and move Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 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 <utility>

int main() {
    std::thread a([] {});
    std::thread b([] {});
    std::thread c;                          // default-constructed: no thread
    std::cout << a.joinable() << b.joinable() << c.joinable() << ' ';
    c = std::move(b);                       // ownership of the thread moves to c
    std::cout << b.joinable() << c.joinable() << ' ';
    a.join();
    c.join();
    std::cout << a.joinable() << c.joinable() << '\n';
    return 0;
}
  • A 110 01 00 Correct
  • B 111 01 00
  • C 110 11 00
  • D 110 01 11
Correct Answer: Option A

A std::thread is joinable while it represents a running (or finished but not yet joined) thread. Moving transfers that, and join() ends it.

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