Thread Pool
Example
#pragma once
#include <future>
#include <vector>
#include <atomic>
#include <queue>
#include <thread>
#include <mutex>
namespace std
{
#define THREADPOOL_MAX_NUM 16
class ThreadPool
{
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 };
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.");
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--;
}
}
};
}
Reference
c++11线程池
线程池讲解(C++)
线程池
基于C++11的threadpool线程池(简洁且可以带任意多的参数)