VEX Engine
Retro looking game engine made in vulkan mostly because i wanted to understand it better.
Loading...
Searching...
No Matches
ThreadPool.hpp
1#pragma once
2#include <vector>
3#include <queue>
4#include <thread>
5#include <mutex>
6#include <condition_variable>
7#include <future>
8#include <functional>
9
10namespace vex {
11 class ThreadPool {
12 public:
13 ThreadPool(size_t threads = std::thread::hardware_concurrency()) : stop(false) {
14 for(size_t i = 0; i < threads; ++i)
15 workers.emplace_back([this] {
16 for(;;) {
17 std::function<void()> task;
18 {
19 std::unique_lock<std::mutex> lock(this->queue_mutex);
20 this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); });
21 if(this->stop && this->tasks.empty()) return;
22 task = std::move(this->tasks.front());
23 this->tasks.pop();
24 }
25 task();
26 }
27 });
28 }
29
30 template<class F, class... Args>
31 auto enqueue(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> {
32 using return_type = std::invoke_result_t<F, Args...>;
33 auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
34 std::future<return_type> res = task->get_future();
35 {
36 std::unique_lock<std::mutex> lock(queue_mutex);
37 if(stop) throw std::runtime_error("enqueue on stopped ThreadPool");
38 tasks.emplace([task](){ (*task)(); });
39 }
40 condition.notify_one();
41 return res;
42 }
43
44 ~ThreadPool() {
45 {
46 std::unique_lock<std::mutex> lock(queue_mutex);
47 stop = true;
48 }
49 condition.notify_all();
50 for(std::thread &worker: workers) worker.join();
51 }
52 private:
53 std::vector<std::thread> workers;
54 std::queue<std::function<void()>> tasks;
55 std::mutex queue_mutex;
56 std::condition_variable condition;
57 bool stop;
58 };
59
60 inline ThreadPool& GetThreadPool() {
61 static ThreadPool pool;
62 return pool;
63 }
64}