Table of Contents

前言

经典面试题,C++手搓线程池。本文提供一个约50行的线程池实现,实现了一个线程池的核心功能。

Code

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <atomic>

using namespace std;

class ThreadPool {
private:
    vector<thread> workers;
    queue<function<void()>> qu;
    mutex mu;
    condition_variable condition;
    atomic<bool> stop;
public:
    explicit ThreadPool(size_t n) {
        for (int i = 0; i < n; i++) {
            workers.emplace_back([this] {
                while (true) {
                    function<void()> task;
                    {
                        unique_lock<mutex> lock(this->mu);
                        this->condition.wait(lock, [this] { return this->stop || !this->qu.empty(); });
                        if (this->stop && this->qu.empty()) {
                            return;
                        }
                        task = std::move(qu.front());
                        qu.pop();
                    }
                    task();
                }
            });
        }
    }

    template<class F, class... Args>
    void push(F &&func, Args &&...args) {
        auto task = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
        {
            unique_lock<mutex> lock(mu);
            if (stop) {
                throw runtime_error("Runtime error");
            }
            qu.emplace([&]() { task(); });
        }
        condition.notify_one();
    }

    ~ThreadPool() {
        stop = true;
        condition.notify_all();
        for (auto &&w: workers) {
            w.join();
        }
    }
};
最后更新于 2024-05-28