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

相关推荐
2501_9307077821 小时前
使用C#代码添加或删除PPT页面
开发语言·c#·powerpoint
攒钱植发21 小时前
嵌入式Linux——解密 ARM 性能优化:LDR 未命中时,为何 STR 还能“插队”?
linux·arm开发·c++·性能优化
百锦再1 天前
金仓数据库提出“三低一平”的迁移理念
开发语言·数据库·后端·python·rust·eclipse·pygame
茉莉玫瑰花茶1 天前
从零搭建 C++ 在线五子棋对战项目:从环境到上线,全流程保姆级教程
开发语言·c++
卡卡酷卡BUG1 天前
2025年Java面试题及详细解答(MySQL篇)
java·开发语言·mysql
野生工程师1 天前
【Python爬虫基础-1】爬虫开发基础
开发语言·爬虫·python
wuwu_q1 天前
彻底讲清楚 Kotlin 的 when 表达式
android·开发语言·kotlin
一匹电信狗1 天前
【C++】哈希表详解(开放定址法+哈希桶)
服务器·c++·leetcode·小程序·stl·哈希算法·散列表
Larry_Yanan1 天前
QML学习笔记(五十一)QML与C++交互:数据转换——基本数据类型
c++·笔记·学习
北城以北88881 天前
SSM--MyBatis框架之动态SQL
java·开发语言·数据库·sql·mybatis