Debian Codegraph @

src/worker.rs

raw symbols SCIP
1 use std::{collections::HashMap, time::Duration};
2
3 use crossbeam_channel::{unbounded, Receiver, Select, Sender};
4
5 use crate::task::{Coroutine, RunResult};
6
7 /// A type which receives notifications from a worker.
8 pub(crate) trait Listener {
9 fn on_task_started(&mut self) {}
10
11 fn on_task_completed(&mut self, _panicked: bool) {}
12
13 fn on_idle(&mut self) -> bool {
14 true
15 }
16 }
17
18 /// A worker thread which belongs to a thread pool and executes tasks.
19 pub(crate) struct Worker<L: Listener> {
20 keep_alive: Duration,
21
22 concurrency_limit: usize,
23
24 /// An initial task this worker should be run before polling for new work.
25 initial_task: Option<Coroutine>,
26
27 /// Pending tasks being run by this worker. Any task that yields without
28 /// being immediately complete is moved to this location to be polled again.
29 pending_tasks: HashMap<usize, Coroutine>,
30
31 /// Queue of new tasks to run. The worker pulls more tasks from this queue
32 /// when idle.
33 queue: Receiver<Coroutine>,
34 immediate_queue: Receiver<Coroutine>,
35
36 /// Channel used to receive notifications from wakers for pending tasks.
37 wake_notifications: (Sender<usize>, Receiver<usize>),
38
39 /// Set to true when the worker is running and wants to consume more work.
40 active: bool,
41
42 /// Receiver of various worker events.
43 listener: L,
44 }
45
46 impl<L: Listener> Worker<L> {
47 /// Create a new worker.
48 pub(crate) fn new(
49 initial_task: Option<Coroutine>,
50 queue: Receiver<Coroutine>,
51 immediate_queue: Receiver<Coroutine>,
52 concurrency_limit: usize,
53 keep_alive: Duration,
54 listener: L,
55 ) -> Self {
56 Self {
57 keep_alive,
58 concurrency_limit,
59 initial_task,
60 pending_tasks: HashMap::new(),
61 queue,
62 immediate_queue,
63 wake_notifications: unbounded(),
64 active: false,
65 listener,
66 }
67 }
68
69 /// Run the worker on the current thread until the work queue is closed.
70 pub(crate) fn run(mut self) {
71 self.active = true;
72
73 if let Some(coroutine) = self.initial_task.take() {
74 self.run_now_or_reschedule(coroutine);
75 }
76
77 // Main worker loop, keep running until the pool shuts down and pending
78 // tasks complete.
79 while self.active || !self.pending_tasks.is_empty() {
80 match self.poll_work() {
81 PollResult::Work(coroutine) => self.run_now_or_reschedule(coroutine),
82 PollResult::Wake(id) => self.run_pending_by_id(id),
83 PollResult::ShutDown => self.active = false,
84 PollResult::Timeout => {
85 // If this worker doesn't have an pending tasks, then we can
86 // potentially shut down the worker due to inactivity.
87 if self.pending_tasks.is_empty() {
88 // If the listener tells us we ought to shut down, then
89 // do so.
90 if self.listener.on_idle() {
91 self.active = false;
92 }
93 }
94 }
95 }
96 }
97 }
98
99 /// Poll for the next work item the worker should work on.
100 fn poll_work(&mut self) -> PollResult {
101 let mut queue_id = None;
102 let mut immediate_queue_id = None;
103 let mut wake_id = None;
104 let mut select = Select::new();
105
106 // As long as we haven't reached our concurrency limit, poll for
107 // additional work.
108 if self.active && self.pending_tasks.len() < self.concurrency_limit {
109 queue_id = Some(select.recv(&self.queue));
110 immediate_queue_id = Some(select.recv(&self.immediate_queue));
111 }
112
113 // If we have pending tasks, poll for waker notifications as well.
114 if !self.pending_tasks.is_empty() {
115 wake_id = Some(select.recv(&self.wake_notifications.1));
116 }
117
118 match select.select_timeout(self.keep_alive) {
119 Ok(op) if Some(op.index()) == queue_id => {
120 if let Ok(coroutine) = op.recv(&self.queue) {
121 PollResult::Work(coroutine)
122 } else {
123 PollResult::ShutDown
124 }
125 }
126 Ok(op) if Some(op.index()) == immediate_queue_id => {
127 if let Ok(coroutine) = op.recv(&self.immediate_queue) {
128 PollResult::Work(coroutine)
129 } else {
130 PollResult::ShutDown
131 }
132 }
133 Ok(op) if Some(op.index()) == wake_id => {
134 PollResult::Wake(op.recv(&self.wake_notifications.1).unwrap())
135 }
136 Ok(_) => unreachable!(),
137 Err(_) => PollResult::Timeout,
138 }
139 }
140
141 fn run_now_or_reschedule(&mut self, mut coroutine: Coroutine) {
142 // If it is possible for this task to yield, we need to prepare a new
143 // waker to receive notifications with.
144 if coroutine.might_yield() {
145 let sender = self.wake_notifications.0.clone();
146 let coroutine_addr = coroutine.addr();
147
148 coroutine.set_waker(waker_fn::waker_fn(move || {
149 let _ = sender.send(coroutine_addr);
150 }));
151 }
152
153 self.listener.on_task_started();
154
155 if let RunResult::Complete {
156 panicked,
157 } = coroutine.run()
158 {
159 self.listener.on_task_completed(panicked);
160 coroutine.complete();
161 } else {
162 // This should never happen if the task promised not to yield!
163 debug_assert!(coroutine.might_yield());
164
165 // Task yielded, so we'll need to reschedule the task to be polled
166 // again when its waker is called. We do this by storing the future
167 // in a collection local to this worker where we can retrieve it
168 // again.
169 //
170 // The benefit of doing it this way instead of sending the future
171 // back through the queue is that the future gets executed (almost)
172 // immediately once it wakes instead of being put behind a queue of
173 // _new_ tasks.
174 self.pending_tasks.insert(coroutine.addr(), coroutine);
175 }
176 }
177
178 fn run_pending_by_id(&mut self, id: usize) {
179 if let Some(coroutine) = self.pending_tasks.get_mut(&id) {
180 if let RunResult::Complete {
181 panicked,
182 } = coroutine.run()
183 {
184 self.listener.on_task_completed(panicked);
185
186 // Task is complete, we can de-allocate it and complete it.
187 self.pending_tasks.remove(&id).unwrap().complete();
188 }
189 }
190 }
191 }
192
193 enum PollResult {
194 /// New work has arrived for this worker.
195 Work(Coroutine),
196
197 /// An existing pending task has woken.
198 Wake(usize),
199
200 /// No activity occurred within the time limit.
201 Timeout,
202
203 /// The thread pool has been shut down.
204 ShutDown,
205 }