Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct POOL {
- bool terminate = false;
- std::atomic_bool done;
- std::mutex queue_mutex;
- std::condition_variable mutex_condition;
- std::vector<std::thread> thread;
- std::queue<std::function<void()>> job;
- void Start(int amount = 0) {
- amount = amount == 0 ? std::thread::hardware_concurrency() : amount;
- for (SINT i = 0; i < amount; i++) {
- this->thread.emplace_back(std::thread(&drx::task::POOL::Loop, this));
- }
- }
- void Loop() {
- while (true) {
- std::function<void()> job;
- {
- std::unique_lock<std::mutex> lock(this->queue_mutex);
- this->mutex_condition.wait(lock, [this] {
- return !this->job.empty() || this->terminate;
- });
- if (this->terminate) {
- return;
- }
- job = this->job.front();
- this->job.pop();
- }
- job();
- }
- }
- void Queue(const std::function<void()>& job) {
- {
- std::unique_lock<std::mutex> lock(this->queue_mutex);
- this->job.push(job);
- }
- this->mutex_condition.notify_one();
- }
- void Stop() {
- {
- std::unique_lock<std::mutex> lock(this->queue_mutex);
- this->terminate = true;
- }
- this->mutex_condition.notify_all();
- for (std::thread& t : this->thread) {
- t.join();
- }
- this->thread.clear();
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment