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