Guest User

Untitled

a guest
May 1st, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. struct POOL {
  2.     bool terminate = false;
  3.     std::atomic_bool done;
  4.     std::mutex queue_mutex;
  5.     std::condition_variable mutex_condition;
  6.     std::vector<std::thread> thread;
  7.     std::queue<std::function<void()>> job;
  8.  
  9.     void Start(int amount = 0) {
  10.         amount = amount == 0 ? std::thread::hardware_concurrency() : amount;
  11.         for (SINT i = 0; i < amount; i++) {
  12.             this->thread.emplace_back(std::thread(&drx::task::POOL::Loop, this));
  13.         }
  14.     }
  15.  
  16.     void Loop() {
  17.         while (true) {
  18.             std::function<void()> job;
  19.             {
  20.                 std::unique_lock<std::mutex> lock(this->queue_mutex);
  21.                 this->mutex_condition.wait(lock, [this] {
  22.                     return !this->job.empty() || this->terminate;
  23.                     });
  24.                 if (this->terminate) {
  25.                     return;
  26.                 }
  27.                 job = this->job.front();
  28.                 this->job.pop();
  29.             }
  30.             job();
  31.         }
  32.     }
  33.  
  34.     void Queue(const std::function<void()>& job) {
  35.         {
  36.             std::unique_lock<std::mutex> lock(this->queue_mutex);
  37.             this->job.push(job);
  38.  
  39.         }
  40.         this->mutex_condition.notify_one();
  41.     }
  42.  
  43.     void Stop() {
  44.         {
  45.             std::unique_lock<std::mutex> lock(this->queue_mutex);
  46.             this->terminate = true;
  47.         }
  48.         this->mutex_condition.notify_all();
  49.         for (std::thread& t : this->thread) {
  50.             t.join();
  51.         }
  52.         this->thread.clear();
  53.     }
  54.  
  55. };
Advertisement
Add Comment
Please, Sign In to add comment