rexylib/src/threadpool.cpp
2020-07-07 15:47:34 -07:00

59 lines
1.3 KiB
C++

#include "rexy/threadpool.hpp"
#include <utility> //move, forward
namespace rexy{
threadpool::threadpool(int numthreads){
for(int i = 0;i < numthreads;++i){
m_workers.emplace_back(&threadpool::worker_loop, this);
}
}
void threadpool::worker_loop(void){
while(m_valid){
write_lock_t lk(m_qlk);
//wait for wakeup, continue if the threadpool is dead or there is a job to run
m_qcv.wait(lk, [this]{return !m_valid || !m_jobs.empty();});
//if the threadpool is dead, kill ourself
if(!m_valid){
return;
}
//steal job from queue
auto job = std::move(m_jobs.front());
m_jobs.pop();
lk.unlock();
job();
}
}
threadpool::threadpool(const threadpool& other):
m_ctor_lock(other.m_qlk),
m_jobs(other.m_jobs),
m_valid(true)
{
for(size_t i = 0;i < other.m_workers.size();++i){
m_workers.emplace_back(&threadpool::worker_loop, this);
}
m_qcv.notify_all();
}
threadpool::threadpool(threadpool&& other):
m_ctor_lock(other.m_qlk),
m_workers(std::move(other.m_workers)),
m_jobs(std::move(other.m_jobs)),
m_valid(other.m_valid.exchange(false))
{
m_ctor_lock.unlock();
}
threadpool::~threadpool(void){
m_valid = false;
//wakeup all workers and end them
m_qcv.notify_all();
for(auto& thread : m_workers){
thread.join();
}
}
}