rexylib/src/threadpool.cpp

82 lines
2.1 KiB
C++

/**
This file is a part of rexy's general purpose library
Copyright (C) 2020 rexy712
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#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)
{
m_ctor_lock.unlock();
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){
invalidate();
for(auto& thread : m_workers){
thread.join();
}
}
void threadpool::invalidate(void){
m_valid = false;
//wakeup all workers and end them
m_qcv.notify_all();
}
}