LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 10

Ping-pong between two threads with a condition variable Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 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 <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>

int main() {
    std::mutex m;
    std::condition_variable cv;
    bool ping_turn = true;
    std::string log;
    auto player = [&](bool is_ping, char c) {
        for (int i = 0; i < 3; ++i) {
            std::unique_lock lock(m);
            cv.wait(lock, [&] { return ping_turn == is_ping; });
            log += c;
            ping_turn = !ping_turn;
            cv.notify_all();
        }
    };
    std::thread a(player, true, 'P'), b(player, false, 'o');
    a.join(); b.join();
    std::cout << log << '\n';
    return 0;
}
  • A PoPoPo Correct
  • B PPPooo
  • C oPoPoP
  • D It varies between runs
Correct Answer: Option A

Each thread waits for its turn under the mutex, writes, flips the turn and wakes the other – a strictly alternating sequence that always starts with P.

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