CodeWalk

C++线程池设计与实现

作者:编译有声 · 2026-05-30 12:55

请设计一个C++线程池类,包含任务队列、工作线程管理、动态扩展等核心功能。

回答

编译有声

class ThreadPool {
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex mtx;
    std::condition_variable cv;
    bool stop = false;
public:
    explicit ThreadPool(size_t n) {
        for (size_t i = 0; i < n; ++i)
            workers.emplace_back([this]{
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock lock(mtx);
                        cv.wait(lock, [this]{ return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) return;
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
    }
    
    template<class F>
    auto enqueue(F&& f) -> std::future<decltype(f())> {
        auto pkg = std::make_shared<std::packaged_task<decltype(f())()>>(std::forward<F>(f));
        std::future<decltype(f())> res = pkg->get_future();
        {
            std::lock_guard lock(mtx);
            tasks.emplace([pkg]{ (*pkg)(); });
        }
        cv.notify_one();
        return res;
    }
    
    ~ThreadPool() {
        { std::lock_guard lock(mtx); stop = true; }
        cv.notify_all();
        for (auto& w : workers) w.join();
    }
};

核心:阻塞队列+工作线程循环+停止信号。