c++实现一个简单的线程池

在 C++11 中实现一个简单的线程池,可以使用标准库中的线程、互斥锁和条件变量来管理线程和任务队列。下面是一个基本的线程池实现示例。

线程池类的实现

cpp 复制代码
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>

class ThreadPool {
public:
    ThreadPool(size_t numThreads);
    ~ThreadPool();

    template<typename F, typename... Args>
    auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>;

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;

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

ThreadPool::ThreadPool(size_t numThreads) : stop(false) {
    for (size_t i = 0; i < numThreads; ++i) {
        workers.emplace_back([this] {
            for (;;) {
                std::function<void()> task;
                {
                    std::unique_lock<std::mutex> lock(this->queueMutex);
                    this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
                    if (this->stop && this->tasks.empty())
                        return;
                    task = std::move(this->tasks.front());
                    this->tasks.pop();
                }
                task();
            }
        });
    }
}

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

template<typename F, typename... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
    using returnType = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<returnType()>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );

    std::future<returnType> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(queueMutex);
        if (stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        tasks.emplace([task]() { (*task)(); });
    }
    condition.notify_one();
    return res;
}

使用线程池

下面是如何使用这个线程池的示例:

cpp 复制代码
#include <iostream>
#include <chrono>

int main() {
    ThreadPool pool(4);

    auto result1 = pool.enqueue([](int a, int b) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        return a + b;
    }, 1, 2);

    auto result2 = pool.enqueue([](int a, int b) {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        return a * b;
    }, 3, 4);

    std::cout << "Result of addition: " << result1.get() << std::endl;
    std::cout << "Result of multiplication: " << result2.get() << std::endl;

    return 0;
}

解释

  1. ThreadPool 构造函数 :初始化工作线程并将其添加到 workers 向量中。每个线程在启动时都会执行一个无限循环,等待任务队列中的任务。
  2. enqueue 方法 :将新任务添加到任务队列中,并返回一个 std::future,以便调用者可以获取任务的结果。使用 std::packaged_taskstd::bind 将任务封装起来。
  3. ThreadPool 析构函数:当线程池对象被销毁时,停止所有线程并等待它们完成当前任务。

这个线程池实现是线程安全的,并且可以处理任意数量的任务。通过使用 std::future,调用者可以异步获取任务的结果。

相关推荐
iCxhust1 小时前
Prj10--8088单板机C语言8259测试(1)
c语言·开发语言
крон4 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan4 小时前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊5 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1185 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之5 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?6 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头6 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
liuyang-neu6 小时前
java内存模型JMM
java·开发语言
利刃大大6 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目