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,调用者可以异步获取任务的结果。

相关推荐
Kay_Liang几秒前
Spring IOC核心原理与实战技巧
java·开发语言·spring boot·spring·ioc·依赖注入·控制反转
xcLeigh15 分钟前
Rust入门:基础语法应用
开发语言·rust·编程·教程·基础语法
Mr.wangh21 分钟前
单例模式&阻塞队列详解
java·开发语言·单例模式·多线程·阻塞队列
nvd1128 分钟前
Lit.js 入门介绍:与 React 的对比
开发语言·javascript·react.js
张较瘦_1 小时前
[论文阅读] 软件工程 | 解决Java项目痛点:DepUpdater如何平衡依赖升级的“快”与“稳”
java·开发语言·论文阅读
蒋星熠1 小时前
全栈开发实战指南:从架构设计到部署运维
运维·c++·python·系统架构·node.js·devops·c5全栈
HalvmånEver1 小时前
Linux:基础开发工具(一)
linux·运维·服务器·开发语言·学习·进阶学习
杜子不疼.1 小时前
【C++】深入拆解二叉搜索树:从递归与非递归双视角,彻底掌握STL容器的基石
开发语言·c++
天若有情6731 小时前
从零实现轻量级C++ Web框架:SimpleHttpServer入门指南
开发语言·前端·c++·后端·mvc·web应用
weixin_456588151 小时前
JVM(java虚拟机)
java·开发语言·jvm