6 #ifndef CNOID_UTIL_THREAD_POOL_H
7 #define CNOID_UTIL_THREAD_POOL_H
13 #include <condition_variable>
20 std::vector<std::thread> threads;
21 std::queue<std::function<void()>> queue;
23 std::condition_variable condition;
24 std::condition_variable finishCondition;
32 for(
int i = 0; i <
size; ++i){
33 threads.emplace_back(std::bind(&ThreadPool::run,
this));
39 std::lock_guard<std::mutex> guard(mutex);
41 condition.notify_all();
44 for(
auto& thread : threads){
45 if(thread.joinable()){
51 int size()
const {
return threads.size(); }
53 void start(std::function<
void()> f) {
54 std::lock_guard<std::mutex> guard(mutex);
56 condition.notify_one();
60 std::unique_lock<std::mutex> lock(mutex);
61 while(!queue.empty() || numActiveThreads > 0){
62 finishCondition.wait(lock);
69 std::unique_lock<std::mutex> lock(mutex, std::try_to_lock_t());
71 if(queue.empty() && numActiveThreads == 0){
80 std::lock_guard<std::mutex> guard(mutex);
81 return numActiveThreads > 0;
87 std::function<void()> f;
89 std::unique_lock<std::mutex> lock(mutex);
91 while (queue.empty() && !isDestroying){
103 std::lock_guard<std::mutex> lock(mutex);
105 if(numActiveThreads == 0){
106 finishCondition.notify_all();