Aether
SDL2 based UI Framework for NX
ThreadPool.hpp
1 #ifndef AETHER_THREADPOOL_HPP
2 #define AETHER_THREADPOOL_HPP
3 
4 #include <condition_variable>
5 #include <deque>
6 #include <functional>
7 #include <mutex>
8 #include <thread>
9 #include <vector>
10 
11 // Forward declare class
12 namespace Aether {
13  class Window;
14 };
15 
16 namespace Aether {
22  class ThreadPool {
23  // Allow the Window class access to the constructor and destructor
24  friend Window;
25 
26  public:
27  // Forward declare nested class
28  class Job;
29 
33  enum class Importance {
34  Normal, //< Normal importance; queue at end
35  High //< High importance; queue at start
36  };
37 
38  private:
42  struct WorkerMetadata {
43  std::condition_variable conditionVariable;
44  std::mutex mutex;
45  int jobID;
47  WorkerMetadata() {
48  this->jobID = 0;
49  }
50  };
51 
52  static ThreadPool * instance;
53  int nextID;
54  bool terminating;
56  std::mutex jobsMutex;
57  std::deque<std::pair<Job *, int>> jobs;
59  std::condition_variable workerConditionVariable;
60  std::vector<WorkerMetadata> workerMetadata;
61  std::vector<std::thread> workers;
66  ThreadPool();
67 
73  void doWork(size_t idx);
74 
79  ~ThreadPool();
80 
81  public:
85  ThreadPool(ThreadPool &) = delete;
86 
90  void operator=(const ThreadPool &) = delete;
91 
98  static ThreadPool * getInstance();
99 
105  size_t maxConcurrentJobs();
106 
114  int queueJob(Job * job, const Importance importance);
115 
122  void removeOrWaitForJob(int id);
123  };
124 };
125 
126 #endif
void operator=(const ThreadPool &)=delete
Prevent assigning.
void removeOrWaitForJob(int id)
Removes the requested job from the queue, or waits until the job is completed if already running...
Base namespace for all Aether related classes and functions.
static ThreadPool * getInstance()
Returns the instance of the ThreadPool. One is created if it does not already exist.
Basic Thread Pool implemented as a singleton.
Definition: ThreadPool.hpp:22
Importance
Enumeration of job importance levels.
Definition: ThreadPool.hpp:33
size_t maxConcurrentJobs()
Returns the maximum number of jobs that can be executed concurrently.
The Window is the root element, which initializes Aether and contains all of the screens/elements to ...
Definition: Window.hpp:27
int queueJob(Job *job, const Importance importance)
Adds a job to the queue. The job object is deleted once it is complete.
Abstract class representing a job for the ThreadPool. It is designed to be inherited to define the jo...
Definition: ThreadPool.Job.hpp:11