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

相关推荐
君义_noip34 分钟前
信息学奥赛一本通 1661:有趣的数列 | 洛谷 P3200 [HNOI2009] 有趣的数列
c++·算法·组合数学·信息学奥赛·csp-s
leaves falling36 分钟前
C语言内存函数-
c语言·开发语言
至为芯2 小时前
IP6537至为芯支持双C口快充输出的45W降压SOC芯片
c语言·开发语言
hele_two2 小时前
快速幂算法
c++·python·算法
OopspoO3 小时前
C++杂记——Name Mangling
c++
yuanmenghao3 小时前
车载Linux 系统问题定位方法论与实战系列 - 车载 Linux 平台问题定位规范
linux·运维·服务器·网络·c++
小羊羊Python3 小时前
SoundMaze v1.0.1正式发布!
开发语言·c++
浩瀚地学3 小时前
【Java】JDK8的一些新特性
java·开发语言·经验分享·笔记·学习
l1t3 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
yugi9878384 小时前
基于遗传算法优化主动悬架模糊控制的Matlab实现
开发语言·matlab