Sunshine v2025.118.151840
Self-hosted game stream host for Moonlight.
thread_pool.h
Go to the documentation of this file.
1
5#pragma once
6
7#include "task_pool.h"
8#include <thread>
9
10namespace thread_pool_util {
15 public:
16 typedef TaskPool::__task __task;
17
18 private:
19 std::vector<std::thread> _thread;
20
21 std::condition_variable _cv;
22 std::mutex _lock;
23
24 bool _continue;
25
26 public:
27 ThreadPool():
28 _continue { false } {}
29
30 explicit ThreadPool(int threads):
31 _thread(threads), _continue { true } {
32 for (auto &t : _thread) {
33 t = std::thread(&ThreadPool::_main, this);
34 }
35 }
36
37 ~ThreadPool() noexcept {
38 if (!_continue) return;
39
40 stop();
41 join();
42 }
43
44 template <class Function, class... Args>
45 auto
46 push(Function &&newTask, Args &&...args) {
47 std::lock_guard lg(_lock);
48 auto future = TaskPool::push(std::forward<Function>(newTask), std::forward<Args>(args)...);
49
50 _cv.notify_one();
51 return future;
52 }
53
54 void
55 pushDelayed(std::pair<__time_point, __task> &&task) {
56 std::lock_guard lg(_lock);
57
58 TaskPool::pushDelayed(std::move(task));
59 }
60
61 template <class Function, class X, class Y, class... Args>
62 auto
63 pushDelayed(Function &&newTask, std::chrono::duration<X, Y> duration, Args &&...args) {
64 std::lock_guard lg(_lock);
65 auto future = TaskPool::pushDelayed(std::forward<Function>(newTask), duration, std::forward<Args>(args)...);
66
67 // Update all timers for wait_until
68 _cv.notify_all();
69 return future;
70 }
71
72 void
73 start(int threads) {
74 _continue = true;
75
76 _thread.resize(threads);
77
78 for (auto &t : _thread) {
79 t = std::thread(&ThreadPool::_main, this);
80 }
81 }
82
83 void
84 stop() {
85 std::lock_guard lg(_lock);
86
87 _continue = false;
88 _cv.notify_all();
89 }
90
91 void
92 join() {
93 for (auto &t : _thread) {
94 t.join();
95 }
96 }
97
98 public:
99 void
100 _main() {
101 while (_continue) {
102 if (auto task = this->pop()) {
103 (*task)->run();
104 }
105 else {
106 std::unique_lock uniq_lock(_lock);
107
108 if (ready()) {
109 continue;
110 }
111
112 if (!_continue) {
113 break;
114 }
115
116 if (auto tp = next()) {
117 _cv.wait_until(uniq_lock, *tp);
118 }
119 else {
120 _cv.wait(uniq_lock);
121 }
122 }
123 }
124
125 // Execute remaining tasks
126 while (auto task = this->pop()) {
127 (*task)->run();
128 }
129 }
130 };
131} // namespace thread_pool_util
Definition task_pool.h:45
Definition thread_pool.h:14
Functions for handling command line arguments.
Definition entry_handler.cpp:41
Declarations for the task pool system.