- thread pool can be paused now
This commit is contained in:
parent
7bb49227e9
commit
1335085326
|
|
@ -11,13 +11,15 @@
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
|
||||||
class ThreadPool {
|
class ThreadPool
|
||||||
|
{
|
||||||
public:
|
public:
|
||||||
ThreadPool(size_t);
|
ThreadPool(size_t);
|
||||||
template<class F, class... Args>
|
template<class F, class... Args>
|
||||||
auto enqueue(F&& f, Args&&... args)
|
auto enqueue(F&& f, Args&&... args)
|
||||||
-> std::future<typename std::result_of<F(Args...)>::type>;
|
-> std::future<typename std::result_of<F(Args...)>::type>;
|
||||||
~ThreadPool();
|
~ThreadPool();
|
||||||
|
void setPause(bool v) { this->pause = v;}
|
||||||
private:
|
private:
|
||||||
// need to keep track of threads so we can join them
|
// need to keep track of threads so we can join them
|
||||||
std::vector< std::thread > workers;
|
std::vector< std::thread > workers;
|
||||||
|
|
@ -27,12 +29,12 @@ private:
|
||||||
// synchronization
|
// synchronization
|
||||||
std::mutex queue_mutex;
|
std::mutex queue_mutex;
|
||||||
std::condition_variable condition;
|
std::condition_variable condition;
|
||||||
bool stop;
|
bool stop, pause;
|
||||||
};
|
};
|
||||||
|
|
||||||
// the constructor just launches some amount of workers
|
// the constructor just launches some amount of workers
|
||||||
inline ThreadPool::ThreadPool(size_t threads)
|
inline ThreadPool::ThreadPool(size_t threads)
|
||||||
: stop(false)
|
: stop(false), pause(false)
|
||||||
{
|
{
|
||||||
for(size_t i = 0;i<threads;++i)
|
for(size_t i = 0;i<threads;++i)
|
||||||
workers.emplace_back(
|
workers.emplace_back(
|
||||||
|
|
@ -45,9 +47,13 @@ inline ThreadPool::ThreadPool(size_t threads)
|
||||||
{
|
{
|
||||||
std::unique_lock<std::mutex> lock(this->queue_mutex);
|
std::unique_lock<std::mutex> lock(this->queue_mutex);
|
||||||
this->condition.wait(lock,
|
this->condition.wait(lock,
|
||||||
[this]{ return this->stop || !this->tasks.empty(); });
|
[this]{ return this->stop || !this->pause || !this->tasks.empty(); });
|
||||||
|
if (this->tasks.empty())
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||||
if(this->stop && this->tasks.empty())
|
if(this->stop && this->tasks.empty())
|
||||||
return;
|
return;
|
||||||
|
if(this->pause)
|
||||||
|
continue;
|
||||||
task = std::move(this->tasks.front());
|
task = std::move(this->tasks.front());
|
||||||
this->tasks.pop();
|
this->tasks.pop();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue