LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading Programs · Question 2

Simple thread pool with a task queue in C++ Solution, output & explanation

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

Implement a ThreadPool with a fixed number of worker threads, a mutex-protected task queue and a condition variable; submit returns a std::future for each task. Submit 20 tasks and sum their results.

Solution
main.cpp
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

class ThreadPool {
    std::vector<std::jthread> workers_;
    std::queue<std::function<void()>> tasks_;
    std::mutex m_;
    std::condition_variable cv_;
    bool stopping_ = false;
public:
    explicit ThreadPool(unsigned n) {
        for (unsigned i = 0; i < n; ++i)
            workers_.emplace_back([this] {
                for (;;) {
                    std::function<void()> task;
                    {
                        std::unique_lock lock(m_);
                        cv_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
                        if (stopping_ && tasks_.empty()) return;
                        task = std::move(tasks_.front());
                        tasks_.pop();
                    }
                    task();                                     // run outside the lock
                }
            });
    }
    template <typename F>
    auto submit(F f) -> std::future<decltype(f())> {
        auto task = std::make_shared<std::packaged_task<decltype(f())()>>(std::move(f));
        auto fut = task->get_future();
        { std::lock_guard lock(m_); tasks_.push([task] { (*task)(); }); }
        cv_.notify_one();
        return fut;
    }
    ~ThreadPool() {
        { std::lock_guard lock(m_); stopping_ = true; }
        cv_.notify_all();                                       // jthreads join after this
    }
};

int main() {
    ThreadPool pool(4);
    std::vector<std::future<long>> results;
    for (int i = 1; i <= 20; ++i) results.push_back(pool.submit([i] { long s = 0; for (int k = 1; k <= i * 1000; ++k) s += k % 7; return s; }));
    long total = 0;
    for (auto& f : results) total += f.get();
    std::cout << "20 tasks, total " << total << '\n';
    return 0;
}

Output Verified by compiling and running

20 tasks, total 629979

Workers sleep on the condition variable until tasks arrive; packaged_task links each task to its future. The destructor wakes everyone with stopping_ set, the workers drain the queue and exit, and the jthreads 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