Libftpp
A modern C++ library
worker_pool.cpp
Go to the documentation of this file.
1 #include "worker_pool.hpp"
2 
3 WorkerPool::WorkerPool(const int& nbWorkers)
4 {
5  _workers.reserve(nbWorkers);
6  _size = nbWorkers;
7  for (size_t i = 0; i < _size; i++)
8  {
9  _workers.emplace_back(&WorkerPool::loop, this);
10  }
11 }
12 
14 {
15  while (!_stop)
16  {
17  std::function<void()> action;
18  {
19  std::unique_lock<std::mutex> lock(_mtx);
20  _cv.wait(lock, [&] { return _stop || !_jobs.empty(); });
21 
22  if (_stop || _jobs.empty())
23  break;
24 
25  action = _jobs.front();
26  _jobs.pop();
27  }
28  action();
29  }
30 }
31 
33 {
34  {
35  std::lock_guard<std::mutex> lock(_mtx);
36  _stop = true;
37  }
38 
39  _cv.notify_all();
40 
41  for (size_t i = 0; i < _size; i++)
42  {
43  if (_workers[i].joinable())
44  _workers[i].join();
45  }
46 
47  _workers.clear();
48 
49  std::lock_guard<std::mutex> lock(_mtx);
50  while (!_jobs.empty())
51  _jobs.pop();
52 }
53 
54 void WorkerPool::addJob(const std::function<void()>& jobToExecute)
55 {
56  {
57  std::lock_guard<std::mutex> lock(_mtx);
58  _jobs.push(jobToExecute);
59  }
60  _cv.notify_one();
61 }
62 
63 void WorkerPool::addJob(IJobs& jobToExecute)
64 {
65  {
66  std::lock_guard<std::mutex> lock(_mtx);
67  _jobs.push([&jobToExecute]() { jobToExecute.start(); });
68  }
69  _cv.notify_one();
70 }
Interface for defining jobs to be executed by the worker pool. Classes implementing this interface mu...
Definition: worker_pool.hpp:63
virtual void start()=0
void loop()
Definition: worker_pool.cpp:13
void addJob(const std::function< void()> &jobToExecute)
Definition: worker_pool.cpp:54
WorkerPool(const int &nbWorkers)
Definition: worker_pool.cpp:3