LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 15

Limiting concurrency with counting_semaphore Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 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 <chrono>
#include <iostream>
#include <semaphore>
#include <thread>
#include <vector>

int main() {
    std::counting_semaphore<3> slots(3);       // at most 3 at a time
    std::atomic<int> inside{0}, peak{0}, finished{0};
    std::vector<std::jthread> pool;
    for (int i = 0; i < 10; ++i)
        pool.emplace_back([&] {
            slots.acquire();
            int now = ++inside;
            int p = peak.load();
            while (now > p && !peak.compare_exchange_weak(p, now)) {}
            std::this_thread::sleep_for(std::chrono::milliseconds(2));
            --inside;
            ++finished;
            slots.release();
        });
    pool.clear();
    std::cout << finished << ' ' << (peak <= 3) << ' ' << inside << '\n';
    return 0;
}
  • A 10 1 0 Correct
  • B 10 0 0
  • C 3 1 0
  • D 10 1 3
Correct Answer: Option A

All ten tasks finish, but the semaphore never lets more than three be inside at once. (The exact peak can be 1, 2 or 3, so the program prints only the check.)

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