31 #ifndef GRT_THREAD_POOL_HEADER 32 #define GRT_THREAD_POOL_HEADER 39 #ifdef GRT_CXX11_ENABLED 43 #include <condition_variable> 46 #endif //GRT_CXX11_ENABLED 48 #include "GRTTypedefs.h" 72 #ifdef GRT_CXX11_ENABLED 83 template<
class F,
class... Args>
84 auto enqueue(F&& f, Args&&... args) -> std::future<
typename std::result_of<F(Args...) >::type>;
85 #endif //GRT_CXX11_ENABLED 93 static unsigned int getThreadPoolSize();
101 static bool setThreadPoolSize(
const unsigned int threadPoolSize );
104 #ifdef GRT_CXX11_ENABLED 105 void launchThreads(
const unsigned int threads);
107 std::vector< std::thread > workers;
108 std::queue< std::function<void()> > tasks;
111 std::mutex queue_mutex;
112 std::condition_variable condition;
113 std::atomic< bool > stop;
115 static std::atomic< unsigned int > threadPoolSize;
116 #endif //GRT_CXX11_ENABLED 119 #ifdef GRT_CXX11_ENABLED 121 template<
class F,
class... Args>
auto ThreadPool::enqueue(F&& func, Args&&... args) -> std::future<
typename std::result_of<F(Args...)>::type>
124 using return_type =
typename std::result_of< F(Args...) >::type;
126 auto task = std::make_shared< std::packaged_task< return_type() > >( std::bind(std::forward<F>( func ), std::forward<Args>(args)...) );
128 std::future< return_type > res = task->get_future();
130 std::unique_lock< std::mutex > lock( queue_mutex );
134 throw std::runtime_error(
"enqueue on stopped ThreadPool");
136 tasks.emplace( [task](){ (*task)(); } );
138 condition.notify_one();
141 #endif //GRT_CXX11_ENABLED 145 #endif //GRT_THREAD_POOL_HEADER