一个简单的 C++ 线程池实现示例,你可以在此基础上根据自己的需要进行修改和扩展

一个简单的 C++ 线程池实现示例,你可以在此基础上根据自己的需要进行修改和扩展

一个用C++实现的线程池

直接上代码,懂得都懂。

第一

#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <functional>

class ThreadPool {
public:
    ThreadPool(size_t threadCount) : m_stop(false) {
        for (size_t i = 0; i < threadCount; ++i) {
            m_threads.emplace_back(std::thread(&ThreadPool::worker, this));
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_stop = true;
        }
        m_condition.notify_all();
        for (auto& thread : m_threads) {
            thread.join();
        }
    }

    template<typename Func, typename... Args>
    void enqueue(Func&& func, Args&&... args) {
        auto task = std::make_shared<std::function<void()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_tasks.push(task);
        }
        m_condition.notify_one();
    }

private:
    void worker() {
        while (true) {
            std::shared_ptr<std::function<void()>> task;
            {
                std::unique_lock<std::mutex> lock(m_mutex);
                m_condition.wait(lock, [this]() { return !m_tasks.empty() || m_stop; });
                if (m_stop && m_tasks.empty()) {
                    return;
                }
                task = m_tasks.front();
                m_tasks.pop();
            }
            (*task)();
        }
    }

    std::vector<std::thread> m_threads;
    std::queue<std::shared_ptr<std::function<void()>>> m_tasks;
    std::mutex m_mutex;
    std::condition_variable m_condition;
    bool m_stop;
};

这个线程池使用了 C++11 的特性,包括 std::thread、std::mutex、std::condition_variable 等,实现了一个可变大小的线程池。

使用方法

  1. 创建一个 ThreadPool 对象,指定线程数量。
  2. 调用 enqueue 方法将需要执行的任务添加到线程池中。
  3. 当不再需要线程池时,调用其析构函数。
  4. enqueue 方法使用了可变参数模板和 std::bind 实现了任务的绑定,可以方便地传递任意数量和类型的参数。如果需要传递引用参数,请使用 std::ref。
  5. 程序结束时应该调用线程池的析构函数,以确保所有线程都被正确地销毁。
  6. 任务应该是无状态的,即不依赖于任何全局变量或外部状态。如果有需要,应该使用互斥锁或其他同步机制来确保线程安全。

结束

如果你觉得我的文章对你有帮助那边就请收藏和关注我,我会不定期的更新技术文章,谢谢!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值