Skip to content

线程池(完整版) ​

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

#include<future>
class ThreadPool
{
public:
    // 构造,创建线程
    explicit ThreadPool(int n):start_(true)
    {
        for(int i=0;i<n;i++)
        {
            threads.emplace_back([this]{workloop();});
        }
    }

    // 析构,销毁线程
    ~ThreadPool()
    {
        start_ = false;
        notempty_.notify_all();
        for(auto& t : threads)
        {
            if(t.joinable()) t.join();
        }
    }

    ThreadPool(const ThreadPool&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;
    
    // 核心变化
    template<typename F,typename ...Args>
    auto submit(F &&f,Args &&...args)
        ->std::future<std::invoke_result_t<F,Args...>>
    {
        using ReturnType = std::invoke_result_t<F,Args...>;
        
        // packaged_task 不可拷贝,而 std::function 要求可拷贝 → shared_ptr 包一层
        auto task = std::make_shared<std::packaged_task<ReturnType()>>(
            std::bind(std::forward<F>(f),std::forward<Args>(args)...));
        
        std::future<ReturnType> result = task->get_future();
        {
            std::unique_lock<std::mutex>lock(mtx_);
            if (!start_)
                throw std::runtime_error("submit() on stopped ThreadPool");
            tasks.emplace([task]{ (*task)(); });
        }
        notempty_.notify_one();
        return result;
    }

private:
    std::atomic<bool> start_;
    std::mutex mtx_;
    std::condition_variable notempty_;
    std::vector<std::thread>threads;
    std::queue<std::function<void()>>tasks;

    void workloop()
    {
        for(;;)
        {
            std::function<void()> task;
            {
                std::unique_lock<std::mutex>lock(mtx_);
                notempty_.wait(lock,[this]{return !start_||!tasks.empty();});

                if(!start_ && tasks.empty()) return;

                if(!tasks.empty())
                {
                    task=std::move(tasks.front());
                    tasks.pop();
                }
            }
            task();
        }
    }
};

/*  threadpool_test.cpp —— 编译: g++ -std=c++20 -pthread threadpool_test.cpp -o tp
#include "threadpool.h"
#include <cstdio>

int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }

int main() {
    ThreadPool pool(4);                       // 4 个 worker

    std::vector<std::future<int>> results;
    for (int i = 30; i < 35; ++i)
        results.emplace_back(pool.submit(fib, i));    // 提交 5 个计算任务

    for (auto &r : results)
        printf("%d\n", r.get());              // get() 阻塞到该任务完成
    return 0;                                 // 析构:等所有任务结束
}
*/