LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 12

Stopping a jthread with request_stop Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 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>
#include <thread>

int main() {
    std::atomic<int> processed{0};
    std::atomic<bool> started{false};
    std::jthread worker([&](std::stop_token st) {
        started = true;
        while (!st.stop_requested()) processed.fetch_add(1);
    });
    while (!started) {}                      // wait until the worker is running
    worker.request_stop();
    worker.join();
    std::cout << worker.get_stop_token().stop_requested() << ' ' << (processed >= 0) << ' ' << worker.joinable() << '\n';
    return 0;
}
  • A 1 1 0 Correct
  • B 0 1 1
  • C 1 0 0
  • D The program never ends
Correct Answer: Option A

request_stop sets the shared stop state that the worker polls; after join the jthread is no longer joinable. (How many items were processed varies, so the program only prints a comparison.)

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