cpputil/include/threadpool.h
2014-09-15 12:14:19 +04:00

44 lines
905 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::shared_ptr<std::packaged_task<R()>> pt_ptr = std::make_shared<std::packaged_task<R()>>(func);
std::future<R> fut = pt_ptr->get_future();
std::function<void()> tf = [pt_ptr] { (*pt_ptr)(); };
_queue.push(tf);
_cv.notify_one();
return fut;
}
private:
void worker_func();
};
#endif // _THREADPOOL_H_