C++11线程池实现

#pragma once

#include <future>

#include <vector>

#include <atomic>

#include <queue>

#include <thread>

#include <mutex>

namespace std {

//线程池最大容量,应尽量设小一点
#define THREADPOOL_MAX_NUM 16

class ThreadPool
{
public:
    ThreadPool(unsigned short size = 1) { AddThread(size); }
    ~ThreadPool()
    {
        if (_run.load())
        {
            Close();
        }
    }

    void Close()
    {
        _run.store(false);
        //唤醒所有线程执行
        _task_cv.notify_all();
        for (thread &th : _pool)
        {
            if (th.joinable())
                th.join();
        }
    }

    //提交一个任务,
    template<class F, class... Args>
    auto commit(F&& f, Args&&... args) ->future<decltype(f(args...))>
    {
        if (!_run)
            throw runtime_error("commit on ThreadPool is stop.");
        // typename std::result_of<F(Args...)>::type, 函数 f 的返回值类型
        using RetType = decltype(f(args...));
        //把函数入口及参数打包
        auto task = make_shared<packaged_task<RetType()>>(bind(forward<F>(f), forward<Args>(args)...));

        future<RetType> future = task->get_future();
        {
            lock_guard<mutex> lock{ _lock };
            _tasks.emplace([task]() {(*task)(); });
        }
#ifdef THREADPOOL_AUTO_GROW if (_id1ThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM) AddThread(1); #endif _task_cv.notify_one(); return future; }

int IdlCount() { return _id1ThrNum; }
    int BusyCount() { return _pool.size(); }

    void AddThread(unsigned short size)
    {
        for (; _pool.size() < THREADPOOL_MAX_NUM && size > 0; --size)
        {
            _pool.emplace_back([this] {
                while (_run.load())
                {
                    Task task;
                    {
                        unique_lock<mutex> lock{ _lock };
                        _task_cv.wait(lock, [this]
                        {
                            return !_run.load() || !_tasks.empty();
                        });
                        if (!_run.load() && _tasks.empty())
                            return;
                        task = move(_tasks.front());
                        _tasks.pop();
                    }
                    _id1ThrNum--;
                    task();
                    _id1ThrNum++;
                }
            });
            _id1ThrNum--;
        }
    }

public:
    //定义类型
    using Task = std::function<void()>;
    //线程池
    vector<thread> _pool;
    //锁
    mutex _lock;
    //任务队列
    queue<Task> _tasks;
    //条件阻塞
    condition_variable _task_cv;
    //线程是否在执行
    atomic<bool> _run{ true };
    //空闲线程
    atomic<int> _id1ThrNum{ 0 };
};
}

猜你喜欢

转载自blog.csdn.net/qq123hongli/article/details/79831401