Untitled Game engine no.5  1.0
Jobs.hpp
1 #ifndef JOB_HPP
2 #define JOB_HPP
3 #include "pch.hpp"
4 #include <queue>
5 #include <thread>
6 #include <mutex>
7 #include <condition_variable>
8 #include <atomic>
9 
10 namespace Engine {
11 
13  const uint8_t MAX_JOB_THREADS = 3;
14 
16  typedef std::function<void(void)> func;
17 
19  class JobSystem {
20  private:
22  std::vector<std::thread> m_Threads;
23 
25  std::mutex mu;
26 
28  std::condition_variable m_Condition;
29 
31  std::queue<func> m_Tasks;
32 
34  bool quit;
35 
36  public:
38  JobSystem() = delete;
39 
43  JobSystem(size_t num_threads) : quit(false) {
44  for (size_t i = 0; i <= num_threads; ++i) {
45  // make sure that we are not exceeding the max number of job threads
46  assert(num_threads <= MAX_JOB_THREADS);
47  m_Threads.emplace_back(
48  [this] {
49  for(;;) {
50  // current task
51  std::function<void()> task;
52 
53  {
54  // block thread until either we are quitting or there is a task available
55  std::unique_lock<std::mutex> lock(this->mu);
56  this->m_Condition.wait(lock,
57  [this]{ return this->quit || !this->m_Tasks.empty(); });
58  // if we're quitting then bail out
59  if(this->quit)
60  return;
61 
62  // get the oldest task
63  task = std::move(this->m_Tasks.front());
64  // remove it
65  this->m_Tasks.pop();
66  }
67  // execute the task
68  task();
69  }
70  });
71  }
72  }
73 
75  void Stop() {
76 
77  // lock the mutex and set quit to true
78  { std::unique_lock<std::mutex> lock(mu);
79  quit = true; }
80 
81  // tell all the worker threads
82  m_Condition.notify_all();
83  for(std::thread &worker: m_Threads)
84  worker.join();
85  }
86 
87  ~JobSystem() {
88  if (!quit)
89  Stop();
90  }
91 
94  void AddJob(func job) {
95  {
96  std::unique_lock<std::mutex> lock(mu);
97 
98  // don't allow enqueueing after stopping the pool
99  if(quit)
100  throw std::runtime_error("enqueue on stopped JobSystem");
101 
102  m_Tasks.emplace([job](){ job(); });
103  }
104  m_Condition.notify_one();
105  }
106 
107  };
108 }
109 
110 #endif
Engine::JobSystem::AddJob
void AddJob(func job)
Definition: Jobs.hpp:94
Engine::JobSystem
A glorified thread pool.
Definition: Jobs.hpp:19
Engine::JobSystem::JobSystem
JobSystem()=delete
delete default constructor
Engine::JobSystem::Stop
void Stop()
Stop the running threads after they finish their current job.
Definition: Jobs.hpp:75
Engine::MAX_JOB_THREADS
const uint8_t MAX_JOB_THREADS
Maximum number of threads used for jobs.
Definition: Jobs.hpp:13
Engine
Definition: Animation.hpp:14
Engine::func
std::function< void(void)> func
Alias for any kind of function pointer.
Definition: Jobs.hpp:16
Engine::JobSystem::JobSystem
JobSystem(size_t num_threads)
Definition: Jobs.hpp:43