inLimbo
TUI Music Player that keeps you in Limbo.
 
Loading...
Searching...
No Matches
workers.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <atomic>
4#include <condition_variable>
5#include <functional>
6#include <future>
7#include <memory>
8#include <mutex>
9#include <queue>
10#include <thread>
11#include <vector>
12
23{
24public:
35 explicit WorkerThreadPool(size_t thread_count = std::thread::hardware_concurrency()) : stop(false)
36 {
37 for (size_t i = 0; i < thread_count; ++i)
38 {
39 workers.emplace_back(
40 [this]
41 {
42 for (;;)
43 {
44 std::function<void()> task;
45 {
46 std::unique_lock<std::mutex> lock(queue_mutex);
47 condition.wait(lock, [this] { return stop || !tasks.empty(); });
48
49 if (stop && tasks.empty())
50 return;
51
52 task = std::move(tasks.front());
53 tasks.pop();
54 }
55 task();
56 }
57 });
58 }
59 }
60
78 template <class F, class... Args>
79 auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>
80 {
81 using return_type = typename std::result_of<F(Args...)>::type;
82
83 auto task = std::make_shared<std::packaged_task<return_type()>>(
84 std::bind(std::forward<F>(f), std::forward<Args>(args)...));
85
86 std::future<return_type> result = task->get_future();
87 {
88 std::unique_lock<std::mutex> lock(queue_mutex);
89
90 // Prevent enqueueing after stopping the pool
91 if (stop)
92 {
93 throw std::runtime_error("Enqueue on stopped ThreadPool");
94 }
95
96 tasks.emplace([task]() { (*task)(); });
97 }
98 condition.notify_one();
99 return result;
100 }
101
110 {
111 {
112 std::unique_lock<std::mutex> lock(queue_mutex);
113 stop = true;
114 }
115 condition.notify_all();
116
117 // Wait for all threads to complete
118 for (std::thread& worker : workers)
119 {
120 if (worker.joinable())
121 {
122 worker.join();
123 }
124 }
125 }
126
127 // Prevent copying and assignment
129 auto operator=(const WorkerThreadPool&) -> WorkerThreadPool& = delete;
130
131private:
132 std::vector<std::thread> workers;
133 std::queue<std::function<void()>> tasks;
134
135 std::mutex queue_mutex;
136 std::condition_variable condition;
137 std::atomic<bool> stop;
138};
WorkerThreadPool(size_t thread_count=std::thread::hardware_concurrency())
Constructs a worker thread pool with a specified number of threads.
Definition workers.hpp:35
WorkerThreadPool(const WorkerThreadPool &)=delete
~WorkerThreadPool()
Gracefully shuts down the thread pool.
Definition workers.hpp:109
auto operator=(const WorkerThreadPool &) -> WorkerThreadPool &=delete
auto enqueue(F &&f, Args &&... args) -> std::future< typename std::result_of< F(Args...)>::type >
Enqueues a task to be executed by the worker threads.
Definition workers.hpp:79