Skip to main content

psync/
multi.rs

1//! A multi-threaded, priority-aware executor (feature `std`).
2//!
3//! [`MultiExecutor`] runs `Send` futures on a fixed set of worker threads that share one ready
4//! queue:
5//!
6//! - **Priorities.** A worker always takes the ready task with the highest priority; tasks of
7//!   equal priority run in the order they became ready (FIFO), as on the single-core
8//!   [`Executor`](crate::Executor). Priorities can change while a task waits; it is re-queued
9//!   under its new priority without losing its place among equals.
10//! - **Fairness.** Strict priorities starve: a busy high-priority task can keep lower ones from
11//!   ever running. With [`MultiExecutor::with_fairness`]`(n)`, every `n`-th task a worker takes is
12//!   the one that has been ready the longest, whatever its priority. A ready task then waits at
13//!   most about `n` times the number of tasks ahead of it in age order.
14//! - **Bounded cooperation.** A task that never awaits cannot be interrupted by any cooperative
15//!   executor. `#[psync::graph(yield_every = N)]` inserts [`yield_now`](crate::yield_now) every
16//!   `N` loop iterations of an async function, so long loops give the scheduler a chance to run
17//!   higher-priority work.
18//!
19//! Wakes are never lost: a task woken while it is being polled is re-queued as soon as the poll
20//! returns (the usual idle / queued / running / notified state machine).
21
22extern crate std;
23
24use alloc::{
25    boxed::Box,
26    collections::{BTreeMap, BTreeSet},
27    sync::Arc,
28    task::Wake,
29    vec::Vec,
30};
31use core::{
32    cmp::Reverse,
33    future::Future,
34    pin::Pin,
35    sync::atomic::{AtomicBool, AtomicU8, AtomicU16, AtomicU64, AtomicUsize, Ordering},
36    task::{Context, Poll, Waker},
37};
38use std::sync::{Condvar, Mutex};
39use std::thread::JoinHandle;
40
41type Job = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
42
43const IDLE: u8 = 0;
44const QUEUED: u8 = 1;
45const RUNNING: u8 = 2;
46const NOTIFIED: u8 = 3;
47const DONE: u8 = 4;
48
49struct Cell {
50    future: Mutex<Option<Job>>,
51    state: AtomicU8,
52    priority: AtomicU16,
53    /// The queue position (FIFO sequence number) while queued.
54    seq: AtomicU64,
55    shared: Arc<Shared>,
56}
57
58#[derive(Default)]
59struct Queue {
60    /// Ready tasks by priority, then age.
61    by_priority: BTreeSet<(Reverse<u16>, u64)>,
62    /// The same tasks by age, with the priority they were queued under.
63    by_age: BTreeMap<u64, (u16, Arc<Cell>)>,
64    next_seq: u64,
65    picks: u64,
66}
67
68struct Shared {
69    queue: Mutex<Queue>,
70    ready: Condvar,
71    idle: Condvar,
72    live: AtomicUsize,
73    shutdown: AtomicBool,
74    fairness: Option<u64>,
75}
76
77impl Shared {
78    fn enqueue(&self, cell: Arc<Cell>) {
79        let mut q = self.queue.lock().expect("queue");
80        let seq = q.next_seq;
81        q.next_seq += 1;
82        let priority = cell.priority.load(Ordering::Acquire);
83        cell.seq.store(seq, Ordering::Release);
84        q.by_priority.insert((Reverse(priority), seq));
85        q.by_age.insert(seq, (priority, cell));
86        drop(q);
87        self.ready.notify_one();
88    }
89
90    /// The next task to run: the highest priority, or every `fairness`-th time the oldest.
91    fn take(&self) -> Option<Arc<Cell>> {
92        let mut q = self.queue.lock().expect("queue");
93        loop {
94            if self.shutdown.load(Ordering::Acquire) {
95                return None;
96            }
97            q.picks += 1;
98            let oldest = self.fairness.is_some_and(|n| q.picks.is_multiple_of(n));
99            let seq = if oldest {
100                q.by_age.keys().next().copied()
101            } else {
102                q.by_priority.iter().next().map(|(_, s)| *s)
103            };
104            if let Some(seq) = seq {
105                let (priority, cell) = q.by_age.remove(&seq).expect("queued task");
106                q.by_priority.remove(&(Reverse(priority), seq));
107                return Some(cell);
108            }
109            q.picks -= 1;
110            q = self.ready.wait(q).expect("queue");
111        }
112    }
113
114    /// Re-key a queued task after a priority change (it keeps its age).
115    fn requeue(&self, cell: &Arc<Cell>) {
116        let mut q = self.queue.lock().expect("queue");
117        let seq = cell.seq.load(Ordering::Acquire);
118        if let Some((old, c)) = q.by_age.get(&seq).map(|(p, c)| (*p, c.clone()))
119            && Arc::ptr_eq(&c, cell)
120        {
121            let new = cell.priority.load(Ordering::Acquire);
122            q.by_priority.remove(&(Reverse(old), seq));
123            q.by_priority.insert((Reverse(new), seq));
124            q.by_age.insert(seq, (new, c));
125        }
126    }
127}
128
129struct CellWaker(Arc<Cell>);
130impl Wake for CellWaker {
131    fn wake(self: Arc<Self>) {
132        self.wake_by_ref();
133    }
134    fn wake_by_ref(self: &Arc<Self>) {
135        wake(&self.0);
136    }
137}
138
139fn wake(cell: &Arc<Cell>) {
140    let mut state = cell.state.load(Ordering::Acquire);
141    loop {
142        let next = match state {
143            IDLE => QUEUED,
144            RUNNING => NOTIFIED,
145            _ => return,
146        };
147        match cell
148            .state
149            .compare_exchange(state, next, Ordering::AcqRel, Ordering::Acquire)
150        {
151            Ok(_) => {
152                if next == QUEUED {
153                    cell.shared.enqueue(cell.clone());
154                }
155                return;
156            }
157            Err(actual) => state = actual,
158        }
159    }
160}
161
162fn run(cell: Arc<Cell>) {
163    cell.state.store(RUNNING, Ordering::Release);
164    let waker = Waker::from(Arc::new(CellWaker(cell.clone())));
165    let mut slot = cell.future.lock().expect("future");
166    let Some(future) = slot.as_mut() else {
167        return;
168    };
169    match future.as_mut().poll(&mut Context::from_waker(&waker)) {
170        Poll::Ready(()) => {
171            *slot = None;
172            drop(slot);
173            cell.state.store(DONE, Ordering::Release);
174            let shared = &cell.shared;
175            if shared.live.fetch_sub(1, Ordering::AcqRel) == 1 {
176                let _q = shared.queue.lock().expect("queue");
177                shared.idle.notify_all();
178            }
179        }
180        Poll::Pending => {
181            drop(slot);
182            // Woken during the poll: run again.
183            if cell
184                .state
185                .compare_exchange(RUNNING, IDLE, Ordering::AcqRel, Ordering::Acquire)
186                .is_err()
187            {
188                cell.state.store(QUEUED, Ordering::Release);
189                cell.shared.enqueue(cell.clone());
190            }
191        }
192    }
193}
194
195/// A priority-aware executor running `Send` futures on worker threads.
196pub struct MultiExecutor {
197    shared: Arc<Shared>,
198    workers: Vec<JoinHandle<()>>,
199}
200
201/// Changes the priority of, wakes, or checks a task of a [`MultiExecutor`].
202#[derive(Clone)]
203pub struct MultiHandle(Arc<Cell>);
204
205impl MultiHandle {
206    pub fn priority(&self) -> u16 {
207        self.0.priority.load(Ordering::Acquire)
208    }
209    /// Change the priority; a queued task moves to its new place right away.
210    pub fn set_priority(&self, priority: u16) {
211        self.0.priority.store(priority, Ordering::Release);
212        if self.0.state.load(Ordering::Acquire) == QUEUED {
213            self.0.shared.requeue(&self.0);
214        }
215    }
216    pub fn wake(&self) {
217        wake(&self.0);
218    }
219    pub fn is_finished(&self) -> bool {
220        self.0.state.load(Ordering::Acquire) == DONE
221    }
222}
223
224impl MultiExecutor {
225    /// `workers` threads with strict priorities (FIFO among equals).
226    pub fn new(workers: usize) -> Self {
227        Self::build(workers, None)
228    }
229
230    /// `workers` threads; every `every`-th pick takes the longest-waiting ready task.
231    pub fn with_fairness(workers: usize, every: u32) -> Self {
232        Self::build(workers, Some(u64::from(every.max(1))))
233    }
234
235    fn build(workers: usize, fairness: Option<u64>) -> Self {
236        let shared = Arc::new(Shared {
237            queue: Mutex::new(Queue::default()),
238            ready: Condvar::new(),
239            idle: Condvar::new(),
240            live: AtomicUsize::new(0),
241            shutdown: AtomicBool::new(false),
242            fairness,
243        });
244        let workers = (0..workers.max(1))
245            .map(|i| {
246                let shared = shared.clone();
247                std::thread::Builder::new()
248                    .name(alloc::format!("psync-worker-{i}"))
249                    .spawn(move || {
250                        while let Some(cell) = shared.take() {
251                            run(cell);
252                        }
253                    })
254                    .expect("spawn worker")
255            })
256            .collect();
257        Self { shared, workers }
258    }
259
260    /// Run `future` at `priority` (larger first).
261    pub fn spawn(
262        &self,
263        priority: u16,
264        future: impl Future<Output = ()> + Send + 'static,
265    ) -> MultiHandle {
266        let cell = Arc::new(Cell {
267            future: Mutex::new(Some(Box::pin(future))),
268            state: AtomicU8::new(QUEUED),
269            priority: AtomicU16::new(priority),
270            seq: AtomicU64::new(0),
271            shared: self.shared.clone(),
272        });
273        self.shared.live.fetch_add(1, Ordering::AcqRel);
274        self.shared.enqueue(cell.clone());
275        MultiHandle(cell)
276    }
277
278    /// Run `future` at `priority` and wait for its output on this thread.
279    pub fn block_on<T: Send + 'static>(
280        &self,
281        priority: u16,
282        future: impl Future<Output = T> + Send + 'static,
283    ) -> T {
284        let (tx, rx) = std::sync::mpsc::sync_channel(1);
285        self.spawn(priority, async move {
286            let _ = tx.send(future.await);
287        });
288        rx.recv().expect("the task panicked")
289    }
290
291    /// Wait until every spawned task has finished.
292    pub fn wait_idle(&self) {
293        let mut q = self.shared.queue.lock().expect("queue");
294        while self.shared.live.load(Ordering::Acquire) > 0 {
295            q = self.shared.idle.wait(q).expect("queue");
296        }
297    }
298}
299
300impl Drop for MultiExecutor {
301    fn drop(&mut self) {
302        self.shared.shutdown.store(true, Ordering::Release);
303        {
304            let _q = self.shared.queue.lock().expect("queue");
305            self.shared.ready.notify_all();
306        }
307        for w in self.workers.drain(..) {
308            let _ = w.join();
309        }
310    }
311}