C++如何实现线程池_C++11手动实现一个简单的固定大小线程池

C++11中可通过std::thread、std::queue、std::mutex、std::condition_variable和std::function实现固定大小线程池,核心包括任务队列、互斥锁、条件变量、线程数组和停止标志;构造时启动指定数量线程并循环等待任务,任务通过enqueue提交并返回std::future支持获取结果,内部使用std::packaged_task包装任务,析构时设置停止标志并通知所有线程退出,确保资源正确释放,适用于避免频繁创建销毁线程的场景。

在C++11中,可以利用标准库提供的std::threadstd::queuestd::mutexstd::condition_variablestd::function等工具手动实现一个简单的固定大小线程池。这种线程池能够复用一组线程来执行多个任务,避免频繁创建和销毁线程的开销。

线程池的基本原理

线程池包含一个任务队列和一组工作线程。任务被提交到队列中,空闲线程从队列中取出任务并执行。主要组件包括:

  • 任务队列:存放待执行的函数对象(std::function
  • 互斥锁:保护任务队列的线程安全访问
  • 条件变:用于通知线程有新任务到来
  • 线程数组:存储固定数量的工作线程
  • 停止标志:控制线程循环退出

实现代码示例

下面是一个简单的固定大小线程池实现:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

class ThreadPool {
public:
    explicit ThreadPool(size_t numThreads) : stop(false) {
        for (size_t i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    std::function task;
                    {
                        std::unique_lock lock(queue_mutex);
                        condition.wait(lock, [this] { return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) return;
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }

    template
    auto enqueue(F&& f) -> std::future::type> {
        using return_type = typename std::result_of::type;

        auto task = std::make_shared>(
            std::forward(f)
        );

        std::future res = task->get_future();
        {
            std::unique_lock lock(queue_mutex);
            if (stop) {
                throw std::runtime_error("enqueue on stopped ThreadPool");
            }
            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    ~ThreadPool() {
        {
            std::unique_lock lock(queue_mutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread &worker : workers) {
            worker.join();
        }
    }

private:
    std::vector workers;
    std::queue> tasks;

    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop;
};

使用方式

创建一个4线程的线程池,并提交几个任务:

int main() {
    ThreadPool pool(4);

    // 提交任务并获取 future
    auto result1 = pool.enqueue([]() {
        std::cout << "Task 1 running on thread " << std::this_thread::get_id() << std::endl;
        return 42;
    });

    auto result2 = pool.enqueue([]() {
        std::cout << "Task 2 running on thread " << std::this_thread::get_id() << std::endl;
        return 84;
    });

    // 等待结果
    std::cout << "Result1: " << result1.get() << std::endl;
    std::cout << "Result2: " << result2.get() << std::endl;

    return 0;
}

关键点说明

该实现的核心机制如下:

  • 构造时启动线程:在构造函数中启动指定数量的线程,每个线程运行一个无限循环等待任务
  • 任务提交与返回值支持:使用std::packaged_task包装任务,使enqueue能返回std::future
  • 优雅关闭:析构函数设置停止标志,唤醒所有线程并等待其结束
  • 线程安全:通过互斥锁保护任务队列,条件变量实现线程阻塞/唤醒
基本上就这些。这个线程池虽然简单,但具备了核心功能,适合学习和小型项目使用。