c++11模板线程池

#pragma once

#include 
#include 
#include 
#include 
#include 
#include 
#include 

namespace std
{
#define MAX_THREAD_NUM 256
class threadpool
{
public:
    inline threadpool(unsigned short size = 4) : stoped(false)
    {
        idlThrNum = size < 1 ? 1 : size;
        for (size = 0; size < idlThrNum; ++size)
        {
            pool.emplace_back([this] {
                while (!stoped)
                {
                    std::function task;
                    {
                        std::unique_lock lock(m_lock);
                        cv_task.wait(lock, [this] { return stoped.load() || !tasks.empty(); });
                        if (!stoped.load() && !tasks.empty())
                        {
                            task = std::move(tasks.front());
                            tasks.pop();
                        }else{
                            continue;
                        }
                    }
                    idlThrNum--;
                    task();
                    idlThrNum++;
                }
                idlThrNum--;
            });
        }
    }

    inline ~threadpool()
    {
        stoped.store(true);
        cv_task.notify_all();
        for (std::thread &t : pool)
        {
            if (t.joinable())
            {
                t.join();
            }
        }
    }

    template 
    auto commit(F &&f, Args &&... args) -> std::future
    {
        if (stoped.load())
        {
            throw std::runtime_error("commit on Threadpool is stopped");
        }

        using RetType = decltype(f(args...));
        auto task = std::make_shared>(std::bind(std::forward(f), std::forward(args)...));
        std::future future = task->get_future();
        {
            std::lock_guard lock(m_lock);
            tasks.emplace([task] {
                (*task)();
            });
        }
        cv_task.notify_one();

        return future;
    }

    int idlCount() { return idlThrNum; }

private:
    using Task = std::function; //任务函数
    std::vector pool;      //线程池
    std::queue tasks;             //任务队列
    std::mutex m_lock;                  //互斥锁
    std::condition_variable cv_task;    //条件阻塞
    std::atomic stoped;           //是否关闭提交
    std::atomic idlThrNum;         //空闲线程数量
};
} // namespace std

       当析构时如果还有未处理完的任务,会丢弃直接退出。

 

你可能感兴趣的:(c++,线程池)