tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

392 lignes · 13648 octetsBrut · Historique
1//! Parking scheduler threads (ADR 0004, Revision 8): each thread sleeps on
2//! its own [`Parker`], so work for one thread wakes that thread alone, and
3//! [`Idle`] wakes a parked thread to look for work only when no thread is
4//! looking already, as Go's `wakep` and Tokio's searching workers do.
5//! Checked with loom (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt
6//! --release --lib park`).
7//!
8//! **Searching.** A thread with nothing of its own to run may search the
9//! others' queues, if fewer than half the threads awake are searching
10//! ([`Idle::try_search`]). A push that leaves work for others to take
11//! calls [`Idle::notify_one`], which wakes a parked thread only if none is
12//! searching, and counts it as searching on its behalf, so a burst of
13//! pushes wakes one thread, not one each. A searcher that finds work stops
14//! searching; if it was the last, it calls `notify_one` again, so wake-ups
15//! spread one at a time while work remains.
16//!
17//! **No lost wake-up.** A thread about to park first lists itself
18//! ([`Idle::announce`]), then stops searching, then re-checks for work;
19//! a pusher publishes its work, then reads the count of searchers. A
20//! `SeqCst` fence on each side, between its write and its read, means
21//! one of them sees the other: the parker finds the work, or the pusher
22//! finds no searcher and the parker listed, and wakes it. A wake-up for one
23//! thread ([`Idle::unpark`]) sets its parker's token, which a later
24//! [`Parker::park`] consumes without sleeping.
25
26#[cfg(loom)]
27use loom::sync::{
28 Condvar, Mutex,
29 atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering, fence},
30};
31use std::time::Duration;
32
33#[cfg(not(loom))]
34use std::sync::{
35 Condvar, Mutex,
36 atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering, fence},
37};
38
39const AWAKE: u8 = 0;
40const PARKED: u8 = 1;
41const NOTIFIED: u8 = 2;
42
43/// One thread's place to sleep, with a wake-up token (as `std::thread`'s
44/// park and unpark): an unpark before the park makes the park return at
45/// once.
46pub(crate) struct Parker {
47 state: AtomicU8,
48 lock: Mutex<()>,
49 wake: Condvar,
50}
51
52impl Parker {
53 pub(crate) fn new() -> Self {
54 Parker {
55 state: AtomicU8::new(AWAKE),
56 lock: Mutex::new(()),
57 wake: Condvar::new(),
58 }
59 }
60
61 /// Sleep until unparked, or `timeout` passes. Returns at once if
62 /// unparked since the last park.
63 pub(crate) fn park(&self, timeout: Option<Duration>) {
64 if self
65 .state
66 .compare_exchange(NOTIFIED, AWAKE, Ordering::SeqCst, Ordering::SeqCst)
67 .is_ok()
68 {
69 return;
70 }
71 let mut guard = self.lock.lock().expect("louise: parker poisoned");
72 if self
73 .state
74 .compare_exchange(AWAKE, PARKED, Ordering::SeqCst, Ordering::SeqCst)
75 .is_err()
76 {
77 // Unparked meanwhile.
78 self.state.store(AWAKE, Ordering::SeqCst);
79 return;
80 }
81 loop {
82 guard = match timeout {
83 None => self.wake.wait(guard).expect("louise: parker poisoned"),
84 Some(t) => {
85 let (guard, waited) = self
86 .wake
87 .wait_timeout(guard, t)
88 .expect("louise: parker poisoned");
89 if waited.timed_out() {
90 self.state.store(AWAKE, Ordering::SeqCst);
91 return;
92 }
93 guard
94 }
95 };
96 if self
97 .state
98 .compare_exchange(NOTIFIED, AWAKE, Ordering::SeqCst, Ordering::SeqCst)
99 .is_ok()
100 {
101 return;
102 }
103 }
104 }
105
106 /// Wake the thread, or make its next park return at once.
107 pub(crate) fn unpark(&self) {
108 if self.state.swap(NOTIFIED, Ordering::SeqCst) == PARKED {
109 // Taken so the notification cannot fall between the parker's
110 // check of `state` and its wait.
111 drop(self.lock.lock().expect("louise: parker poisoned"));
112 self.wake.notify_one();
113 }
114 }
115}
116
117/// The scheduler's threads as parked or searching.
118pub(crate) struct Idle {
119 parkers: Box<[Parker]>,
120 /// Set by [`Idle::notify_one`] for the thread it wakes: that thread is
121 /// already counted in `searching`.
122 handed: Box<[AtomicBool]>,
123 searching: AtomicUsize,
124 /// Threads listed as parked, most recent last.
125 parked: Mutex<Vec<usize>>,
126 num_parked: AtomicUsize,
127}
128
129impl Idle {
130 pub(crate) fn new(threads: usize) -> Self {
131 Idle {
132 parkers: (0..threads).map(|_| Parker::new()).collect(),
133 handed: (0..threads).map(|_| AtomicBool::new(false)).collect(),
134 searching: AtomicUsize::new(0),
135 parked: Mutex::new(Vec::with_capacity(threads)),
136 num_parked: AtomicUsize::new(0),
137 }
138 }
139
140 fn threads(&self) -> usize {
141 self.parkers.len()
142 }
143
144 /// Start searching other threads' queues, unless half the threads awake
145 /// are searching already.
146 pub(crate) fn try_search(&self) -> bool {
147 let awake = self.threads() - self.num_parked.load(Ordering::SeqCst);
148 let searching = self.searching.load(Ordering::SeqCst);
149 if searching > 0 && 2 * searching >= awake {
150 return false;
151 }
152 self.searching.fetch_add(1, Ordering::SeqCst);
153 true
154 }
155
156 /// Stop searching; returns whether this was the last searcher.
157 pub(crate) fn stop_searching(&self) -> bool {
158 self.searching.fetch_sub(1, Ordering::SeqCst) == 1
159 }
160
161 /// Work was published that another thread could take: wake a parked
162 /// thread to search for it, unless one is searching already.
163 pub(crate) fn notify_one(&self) {
164 fence(Ordering::SeqCst);
165 if self.searching.load(Ordering::SeqCst) > 0 || self.num_parked.load(Ordering::SeqCst) == 0
166 {
167 return;
168 }
169 let woken = {
170 let mut parked = self.parked.lock().expect("louise: idle poisoned");
171 if self.searching.load(Ordering::SeqCst) > 0 {
172 return;
173 }
174 let woken = parked.pop();
175 if let Some(thread) = woken {
176 self.num_parked.fetch_sub(1, Ordering::SeqCst);
177 self.searching.fetch_add(1, Ordering::SeqCst);
178 // Under the lock: `unlist` reads it under the same lock, so
179 // a thread off the list always sees whether it was handed.
180 self.handed[thread].store(true, Ordering::SeqCst);
181 }
182 woken
183 };
184 if let Some(thread) = woken {
185 self.parkers[thread].unpark();
186 }
187 }
188
189 /// Wake thread `thread`: work was queued for it alone.
190 pub(crate) fn unpark(&self, thread: usize) {
191 self.parkers[thread].unpark();
192 }
193
194 /// Wake every thread (the scheduler finished, or needs an idle thread).
195 pub(crate) fn unpark_all(&self) {
196 for parker in &self.parkers {
197 parker.unpark();
198 }
199 }
200
201 /// Wake one parked thread, searching or not (an idle thread is needed).
202 pub(crate) fn unpark_any(&self) {
203 let woken = {
204 let mut parked = self.parked.lock().expect("louise: idle poisoned");
205 let woken = parked.pop();
206 if woken.is_some() {
207 self.num_parked.fetch_sub(1, Ordering::SeqCst);
208 }
209 woken
210 };
211 if let Some(thread) = woken {
212 self.parkers[thread].unpark();
213 }
214 }
215
216 /// List `thread` as parked, before it re-checks for work and parks.
217 pub(crate) fn announce(&self, thread: usize) {
218 let mut parked = self.parked.lock().expect("louise: idle poisoned");
219 parked.push(thread);
220 self.num_parked.fetch_add(1, Ordering::SeqCst);
221 }
222
223 /// After [`Idle::announce`] (and `stop_searching` if it searched),
224 /// before re-checking for work.
225 pub(crate) fn fence(&self) {
226 fence(Ordering::SeqCst);
227 }
228
229 /// Sleep `thread` (announced) until woken or `timeout`. Returns whether
230 /// it woke as a searcher ([`Idle::notify_one`] counted it).
231 pub(crate) fn park(&self, thread: usize, timeout: Option<Duration>) -> bool {
232 self.parkers[thread].park(timeout);
233 self.unlist(thread)
234 }
235
236 /// Take `thread` off the parked list, if still on it (it found work
237 /// before parking, or woke for another reason than `notify_one`).
238 /// Returns whether `notify_one` woke it as a searcher.
239 pub(crate) fn unlist(&self, thread: usize) -> bool {
240 let mut parked = self.parked.lock().expect("louise: idle poisoned");
241 if let Some(at) = parked.iter().rposition(|&t| t == thread) {
242 parked.remove(at);
243 self.num_parked.fetch_sub(1, Ordering::SeqCst);
244 }
245 self.handed[thread].swap(false, Ordering::SeqCst)
246 }
247
248 /// Threads listed as parked now.
249 #[cfg(test)]
250 pub(crate) fn parked(&self) -> usize {
251 self.num_parked.load(Ordering::SeqCst)
252 }
253
254 /// Threads searching now.
255 #[cfg(test)]
256 pub(crate) fn searching(&self) -> usize {
257 self.searching.load(Ordering::SeqCst)
258 }
259}
260
261#[cfg(all(test, loom))]
262mod loom_models {
263 use super::*;
264 use loom::sync::Arc;
265 use loom::sync::atomic::AtomicUsize;
266 use loom::thread;
267
268 /// An unpark before or during a park is never lost.
269 #[test]
270 fn unpark_wakes_a_park() {
271 loom::model(|| {
272 let parker = Arc::new(Parker::new());
273 let flag = Arc::new(AtomicUsize::new(0));
274 let waker = {
275 let (parker, flag) = (parker.clone(), flag.clone());
276 thread::spawn(move || {
277 flag.store(1, Ordering::SeqCst);
278 parker.unpark();
279 })
280 };
281 while flag.load(Ordering::SeqCst) == 0 {
282 parker.park(None);
283 }
284 waker.join().unwrap();
285 });
286 }
287
288 /// A thread parking for lack of work, against a push of work and a
289 /// `notify_one`: the thread finds the work, or is woken for it.
290 #[test]
291 fn notify_one_reaches_a_parking_searcher() {
292 loom::model(|| {
293 let idle = Arc::new(Idle::new(2));
294 let work = Arc::new(AtomicUsize::new(0));
295 let pusher = {
296 let (idle, work) = (idle.clone(), work.clone());
297 thread::spawn(move || {
298 work.store(1, Ordering::SeqCst);
299 idle.notify_one();
300 })
301 };
302 // Thread 1: searching, found nothing, parks.
303 assert!(idle.try_search());
304 loop {
305 idle.announce(1);
306 let _ = idle.stop_searching();
307 idle.fence();
308 if work.load(Ordering::SeqCst) == 1 {
309 // `notify_one` may have handed it the search already.
310 if idle.unlist(1) {
311 let _ = idle.stop_searching();
312 }
313 break;
314 }
315 if idle.park(1, None) {
316 // Woken to search.
317 if work.load(Ordering::SeqCst) == 1 {
318 let _ = idle.stop_searching();
319 break;
320 }
321 } else {
322 assert!(idle.try_search());
323 }
324 }
325 pusher.join().unwrap();
326 assert_eq!(idle.searching(), 0);
327 });
328 }
329
330 /// Work for one thread, against that thread parking: it is woken.
331 #[test]
332 fn unpark_reaches_its_thread() {
333 loom::model(|| {
334 let idle = Arc::new(Idle::new(2));
335 let inbound = Arc::new(AtomicUsize::new(0));
336 let pusher = {
337 let (idle, inbound) = (idle.clone(), inbound.clone());
338 thread::spawn(move || {
339 inbound.store(1, Ordering::SeqCst);
340 idle.unpark(0);
341 })
342 };
343 while inbound.load(Ordering::SeqCst) == 0 {
344 idle.announce(0);
345 idle.fence();
346 if inbound.load(Ordering::SeqCst) == 1 {
347 let _ = idle.unlist(0);
348 break;
349 }
350 let _ = idle.park(0, None);
351 }
352 pusher.join().unwrap();
353 });
354 }
355}
356
357#[cfg(all(test, not(loom)))]
358mod tests {
359 use super::*;
360
361 #[test]
362 fn notify_one_wakes_one_searcher_at_a_time() {
363 let idle = Idle::new(4);
364 idle.announce(1);
365 idle.announce(2);
366 idle.notify_one();
367 assert_eq!(idle.searching(), 1, "the woken thread counts as searching");
368 idle.notify_one();
369 assert_eq!(idle.searching(), 1, "no second thread while one searches");
370 assert!(idle.park(2, None), "woke as a searcher");
371 assert!(idle.stop_searching());
372 assert!(!idle.unlist(1), "still parked, not handed");
373 }
374
375 #[test]
376 fn at_most_half_the_awake_threads_search() {
377 let idle = Idle::new(4);
378 assert!(idle.try_search());
379 assert!(idle.try_search());
380 assert!(!idle.try_search(), "two of four");
381 idle.announce(3);
382 assert!(!idle.try_search(), "two of three awake");
383 }
384
385 #[test]
386 fn an_early_unpark_makes_the_park_return() {
387 let parker = Parker::new();
388 parker.unpark();
389 parker.park(None);
390 parker.park(Some(Duration::from_millis(1)));
391 }
392}