LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading Programs · Question 5

Three-stage thread pipeline with blocking queues in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Build a pipeline: a reader thread produces numbers 1–50, a worker thread squares them, and a writer thread sums the results, connected by two thread-safe blocking queues that can be closed.

Solution
main.cpp
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <optional>
#include <queue>
#include <thread>

template <typename T>
class Channel {
    std::queue<T> q_;
    std::mutex m_;
    std::condition_variable cv_;
    bool closed_ = false;
public:
    void send(T v) { { std::lock_guard l(m_); q_.push(std::move(v)); } cv_.notify_one(); }
    void close() { { std::lock_guard l(m_); closed_ = true; } cv_.notify_all(); }
    std::optional<T> receive() {
        std::unique_lock l(m_);
        cv_.wait(l, [this] { return !q_.empty() || closed_; });
        if (q_.empty()) return std::nullopt;
        T v = std::move(q_.front());
        q_.pop();
        return v;
    }
};

int main() {
    Channel<int> raw, squared;
    long sum = 0;
    int count = 0;
    std::jthread reader([&] { for (int i = 1; i <= 50; ++i) raw.send(i); raw.close(); });
    std::jthread worker([&] { while (auto v = raw.receive()) squared.send(*v * *v); squared.close(); });
    std::jthread writer([&] { while (auto v = squared.receive()) { sum += *v; ++count; } });
    writer.join();                               // the writer finishes after the channels are closed
    std::cout << count << " values, sum of squares " << sum << '\n';
    return 0;
}

Output Verified by compiling and running

50 values, sum of squares 42925

Each stage runs in its own thread; closing a channel lets the next stage finish once it is drained. sum and count are touched only by the writer thread and read after join().

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