#pragma once /* Simple thread pool, no fancy stuff. It is thread safe (i.e. concurrent adds). Threads terminate if there is no work (we need wait_and_pop for that). Works best if all work is added, and then run. Doesn't care about exceptions. */ #include #include #include #include "lock_queue.hpp" struct thread_pool { void add(std::function f){ work.push(f); } void run(int number_of_threads){ for(int i = 0; i < number_of_threads; ++i){ threads.emplace_back([this]{ auto x = work.try_pop(); while(x){ (*x)(); x = work.try_pop(); } }); } } ~thread_pool(){ for(auto & t : threads) t.join(); } private: queue> work; std::vector threads; };