c++11实现线程池

c++11实现的线程池,采用的是函数式编程接口的方式来处理各个任务,比传统的通过实现 Runnable接口的方式更加简洁方便。

添加头文件

#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <future>
#include <memory>

添加私有的数据

std::vector<std::thread> m_threads;

std::queue<std::function<void()>> m_tasks;
std::mutex m_mtx;
std::condition_variable m_cond;

bool m_bStart;

添加公有的接口

public:    
    ThreadPool(size_t nThreadSize = 10)
    {
        Start(nThreadSize);
    }

    ThreadPool(const ThreadPool&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;
    ThreadPool(ThreadPool&&) = delete;
    ThreadPool& operator=(ThreadPool&&) = delete;
    ~ThreadPool()
    {
        Stop();
    }

    template<class F, class... Args>
    auto submit(F&& func, Args&&... args)->
        std::future<typename std::result_of<F(Args...)>::type>
    {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto sptr = std::make_shared<
            std::packaged_task<return_type()>
        >(std::bind(std::forward<F>(func), std::forward<Args>(args)...));

        std::future<return_type> ret = sptr->get_future();
        {
            std::unique_lock<std::mutex> lock(m_mtx);

            if (!m_bStart)
            {
                throw std::runtime_error("the threadpool has finish,do not enqueue!");
            }

            m_tasks.push([sptr] {(*sptr)(); });
            m_cond.notify_one();
        }

        return ret;
    }
private:
    void Start(size_t nThreadSize)
    {
        std::unique_lock<std::mutex> lock(m_mtx);
        m_bStart = true;
        m_threads.push_back(std::thread(&ThreadPool::Run,this));
    }

    void Stop()
    {
        {
            std::unique_lock<std::mutex> lock(m_mtx);
            m_bStart = false;
            m_cond.notify_all();
        }
        for (auto& thd : m_threads)
        {
            if (thd.joinable())
            {
                thd.join();
            }
        }
        return;
    }

    void Run()
    {
        while (true)
        {
            std::unique_lock<std::mutex> lock(m_mtx);
            while (m_bStart && m_tasks.empty())
            {
                m_cond.wait(lock);
            }
            if (!m_bStart)
            {
                return;
            }
            auto task = std::move(m_tasks.front());
            m_tasks.pop();
            lock.unlock();
            
            task();
        }
    }

对 submit这个接口的解析:

result_of的具体用法参考我的另一篇博客:result_of 用法

1. 通过 result_of这个c++11接口来萃取模板函数的返回值。

2. 将模板参数和模板函数通过 packaged_task去打包,因为packaged_task因为不能直接使用submit的func和args,所以采用bind的方式获取参数。

3.因为我们的任务队列存放是是functional,而不能直接存放packaged_task,所以我们需要通过lambda的方式将packaged_task给包装起来,但是因为packaged_task不可以拷贝构造,所以我们采用 make_shared的方式构造一个 shared_ptr<...>()对象,然后让lambda的捕捉列表获取该对象。

4.因为一般情况下,我们需要得到执行的结果,而且是异步的方式,所以submit返回一个future对象,这样我们在合适的位置调用 future.get()就可以得到该函数的执行结果。

调用示例:

ThreadPool g_threadpool;

int func(int a, int b)
{
    return a + b;
}
void test()
{
    g_threadpool.submit([] {
        std::cout << "test\n";
    });

    g_threadpool.submit([](int a) {
        std::cout << a<<"\n";
    },2);

    std::future<int> ft = g_threadpool.submit(func,1,2);

    std::cout << ft.get() << "\n";
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值