cpputil/include/threadpool.h

42 lines
790 B
C++

#ifndef _THREADPOOL_H_
#define _THREADPOOL_H_
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <queue>
#include <vector>
#include <future>
class threadpool
{
private:
std::size_t _concurrency;
std::queue<std::function<void()>> _queue;
std::mutex _mutex;
std::condition_variable _cv;
std::vector<std::thread> _workers;
bool _enabled;
public:
threadpool();
threadpool(std::size_t concurrency);
~threadpool();
template <typename R> std::future<R> add_task(std::function<R()> func)
{
std::lock_guard<std::mutex> lock(_mutex);
std::packaged_task<R()> pt(func);
std::future<R> fut = pt.get_future();
_queue.push([&pt]{ pt(); });
_cv.notify_all();
return fut;
}
private:
void worker_func();
};
#endif // _THREADPOOL_H_