| @@ -12,35 +12,42 @@ |
| 12 | 12 | //! them an `ExitSignal` if they trap exits; monitors receive `Down`; |
| 13 | 13 | //! - when `main` stops, the other actors are stopped. |
| 14 | 14 | //! |
| 15 | | −//! **Threads.** `TILC_THREADS` scheduler threads (default: one per core) |
| 16 | | −//! take actors from one run queue, so an actor may run on a different |
| 17 | | −//! thread after each suspension. With `TILC_THREADS=1` the order is the |
| 18 | | −//! interpreter's, and `tests/run` outputs are reproducible. Messages are |
| 19 | | −//! made thread-safe when sent (`send`: move, share or copy). |
| 15 | +//! **Threads** (ADR 0004, Revision 2). `TILC_THREADS` scheduler threads |
| 16 | +//! (default: one per core) each have a FIFO run queue; a thread with |
| 17 | +//! nothing to do steals from the shared queue, then from the others. An |
| 18 | +//! actor may run on a different thread after each suspension. With |
| 19 | +//! `TILC_THREADS=1` there is one queue, the order is the interpreter's, |
| 20 | +//! and `tests/run` outputs are reproducible. Messages are made |
| 21 | +//! thread-safe when sent (`send`: move, share or copy). |
| 20 | 22 | //! |
| 21 | 23 | //! **What is shared, and how.** Everything other actors may touch (the |
| 22 | | −//! mailbox, links, the wait state: [`Proc`]) lives in [`Sched`], behind |
| 23 | | −//! one mutex. An [`Actor`] holds what only the thread running it touches |
| 24 | | −//! (its context, drop worklist, yielders), plus an atomic kill flag. A |
| 24 | +//! mailbox, links, monitors, the wait state: [`Proc`]) is behind the |
| 25 | +//! actor's own lock, in its [`Cell`]. An [`Actor`] holds what only the |
| 26 | +//! thread running it touches (its context, drop worklist, yielders). A |
| 25 | 27 | //! wake-up queues an actor only if it is suspended; if it is still on its |
| 26 | 28 | //! way to suspending, the thread running it queues it when it yields, so |
| 27 | | −//! no wake-up is lost or doubled. |
| 29 | +//! no wake-up is lost or doubled (`handoff::RunState`). Timers, sockets |
| 30 | +//! and blocking calls are behind one control lock, taken off the hot |
| 31 | +//! paths of sending, receiving and scheduling. |
| 28 | 32 | //! |
| 29 | 33 | //! **Logical exit and unwinding are separate.** An actor exits (monitors |
| 30 | 34 | //! and links are notified) the moment it is killed, as in the interpreter. |
| 31 | 35 | //! Its fiber then runs once more to unwind, dropping everything it holds. |
| 32 | | −//! A fiber is never dropped while suspended, because corosensei would |
| 33 | | −//! force-unwind C frames. |
| 36 | +//! A fiber is never dropped while suspended, because its frames would |
| 37 | +//! never release what they hold. |
| 34 | 38 | //! |
| 35 | | −//! Invariant: the scheduler lock is never held while actor code runs, and |
| 36 | | −//! never taken twice by one thread. |
| 39 | +//! Invariant: no scheduler lock is held while actor code runs. |
| 37 | 40 | |
| 38 | | −use std::collections::{HashMap, HashSet, VecDeque}; |
| 39 | | −use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; |
| 40 | | −use std::sync::{Condvar, Mutex, MutexGuard}; |
| 41 | +use std::cell::RefCell; |
| 42 | +use std::cmp::Reverse; |
| 43 | +use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque}; |
| 44 | +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; |
| 45 | +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock}; |
| 41 | 46 | |
| 42 | | −use corosensei::stack::DefaultStack; |
| 43 | | −use corosensei::{Coroutine, CoroutineResult, Yielder}; |
| 47 | +use crossbeam_deque::{Injector, Steal, Stealer, Worker}; |
| 48 | + |
| 49 | +use crate::fiber::{Coroutine, CoroutineResult, Stack, Yielder}; |
| 50 | +use crate::handoff::{RunState, Sleepers}; |
| 44 | 51 | |
| 45 | 52 | use crate::abi::{ |
| 46 | 53 | Ctx, UNIT, Value, YIELD_FINAL, YIELD_KILL, YIELD_NONE, YIELD_PANIC, int, int_get, |
| @@ -51,7 +58,7 @@ use crate::values::{closure_code, string_bytes}; |
| 51 | 58 | /// Function entries an actor may make before it yields (the interpreter |
| 52 | 59 | /// counts calls the same way). |
| 53 | 60 | pub(crate) const REDUCTIONS: i32 = 2000; |
| 54 | | −/// Virtual size of an actor stack (plus a guard page from corosensei). |
| 61 | +/// Virtual size of an actor stack (plus a guard page, see `fiber`). |
| 55 | 62 | const STACK_SIZE: usize = 256 * 1024; |
| 56 | 63 | /// Compiled actors get larger stacks (committed lazily), so native |
| 57 | 64 | /// recursion depth matches the interpreter's. |
| @@ -74,16 +81,16 @@ type ActorClosureFn = unsafe extern "C" fn(*mut Ctx, Value) -> Value; |
| 74 | 81 | |
| 75 | 82 | /// An actor's fiber, movable between scheduler threads. |
| 76 | 83 | /// The second field is the stack size. |
| 77 | | −struct Fiber(Coroutine<(), (), (), DefaultStack>, usize); |
| 78 | | − |
| 79 | | −// SAFETY: corosensei fibers are `!Send` because code on them could keep |
| 80 | | −// references to thread-local storage across a suspension, which would then |
| 81 | | −// resume on another thread. Code on actor fibers never does: generated C |
| 82 | | −// uses no thread-locals (its state is in `tl_ctx`), and the runtime keeps |
| 83 | | −// all actor state in `Actor`/`Sched`; Rust's own thread-locals (stdout |
| 84 | | −// locks, panic counts) are never held across a suspension, which only |
| 85 | | −// happens in `preempt_root` and `handlers`. Revisit with the runtime's own |
| 86 | | −// context switch (issue #35). |
| 84 | +struct Fiber(Coroutine<(), (), ()>, usize); |
| 85 | + |
| 86 | +// SAFETY: a suspended fiber is its stack and saved registers (`fiber`), |
| 87 | +// so it can resume on any thread, provided the code on it keeps no |
| 88 | +// references to thread-local storage across a suspension. Code on actor |
| 89 | +// fibers never does: generated C uses no thread-locals (its state is in |
| 90 | +// `tl_ctx`), and the runtime keeps all actor state in `Actor`/`Sched`; |
| 91 | +// Rust's own thread-locals (stdout locks, panic counts) are never held |
| 92 | +// across a suspension, which only happens in `preempt_root` and |
| 93 | +// `handlers` (ADR 0011). |
| 87 | 94 | unsafe impl Send for Fiber {} |
| 88 | 95 | |
| 89 | 96 | enum Body { |
| @@ -119,25 +126,25 @@ pub(crate) enum Wait { |
| 119 | 126 | Io, |
| 120 | 127 | } |
| 121 | 128 | |
| 122 | | −/// What only the thread running the actor touches, plus the kill flag. |
| 129 | +/// What only the thread running the actor touches. |
| 123 | 130 | pub struct Actor { |
| 124 | 131 | ctx: Ctx, |
| 125 | 132 | pub(crate) pid: i64, |
| 126 | 133 | next_marker: u64, |
| 127 | | − /// Set (under the scheduler lock) when the actor exits; read by the |
| 128 | | − /// actor at its safe points. |
| 129 | | − kill_requested: AtomicBool, |
| 130 | 134 | drops: DropStack, |
| 131 | 135 | yielder: *const Yielder<(), ()>, |
| 132 | 136 | /// The `ctl` handler fiber running now, or null on the actor's own |
| 133 | 137 | /// stack (see `handlers`). |
| 134 | 138 | handler: *const crate::handlers::HandlerYielder, |
| 135 | 139 | sched: *const Shared, |
| 140 | + /// Its shared half (the table keeps it alive while the actor lives). |
| 141 | + cell: *const Cell, |
| 136 | 142 | } |
| 137 | 143 | |
| 138 | 144 | impl Actor { |
| 139 | 145 | pub(crate) fn kill_requested(&self) -> bool { |
| 140 | | − self.kill_requested.load(Ordering::Acquire) |
| 146 | + // SAFETY: the cell outlives the actor's fiber. |
| 147 | + unsafe { (*self.cell).kill.load(Ordering::Acquire) } |
| 141 | 148 | } |
| 142 | 149 | } |
| 143 | 150 | |
| @@ -183,135 +190,155 @@ impl Mailbox { |
| 183 | 190 | } |
| 184 | 191 | } |
| 185 | 192 | |
| 186 | | −/// An actor's OTP state, which other actors read and write (under the |
| 187 | | −/// scheduler lock). |
| 193 | +/// An actor's OTP state, which other actors read and write under the |
| 194 | +/// actor's lock. |
| 188 | 195 | pub(crate) struct Proc { |
| 189 | 196 | pub(crate) mailbox: Mailbox, |
| 190 | 197 | pub(crate) wait: Wait, |
| 191 | 198 | /// What a parked operation returns when woken. |
| 192 | 199 | pub(crate) wake: Value, |
| 193 | 200 | pub(crate) links: Vec<i64>, |
| 201 | + /// (watcher, tag): who receives `Down` when this actor exits. |
| 202 | + pub(crate) monitors: Vec<(i64, i64)>, |
| 194 | 203 | pub(crate) trap: bool, |
| 195 | 204 | pub(crate) exits_tag: Option<i64>, |
| 196 | 205 | /// While `wait` is `Receive`: the tags waited on, and whether the |
| 197 | 206 | /// answer carries the tag (`receive_any`). |
| 198 | 207 | pub(crate) waiting_tags: Vec<i64>, |
| 199 | 208 | pub(crate) waiting_any: bool, |
| 209 | + /// Counts waits, so a timer set for an earlier one is ignored. |
| 210 | + wait_gen: u64, |
| 200 | 211 | /// Exited (logically); its fiber may still have to unwind. |
| 201 | 212 | pub(crate) dead: bool, |
| 213 | + run: RunState<Fiber>, |
| 214 | +} |
| 215 | + |
| 216 | +impl Proc { |
| 217 | + /// Make the actor ready; its parked operation returns `value`. |
| 218 | + /// Returns whether the caller must [`Shared::schedule`] it (after |
| 219 | + /// releasing the lock). |
| 220 | + pub(crate) fn wake(&mut self, value: Value) -> bool { |
| 221 | + self.wait = Wait::Ready; |
| 222 | + self.wake = value; |
| 223 | + self.run.wake() |
| 224 | + } |
| 225 | + |
| 226 | + /// Wake it unless it is ready or in a blocking call. |
| 227 | + fn interrupt(&mut self) -> bool { |
| 228 | + if self.wait != Wait::Ready && self.wait != Wait::Blocking { |
| 229 | + return self.wake(UNIT); |
| 230 | + } |
| 231 | + false |
| 232 | + } |
| 233 | + |
| 234 | + /// Start waiting as `wait`; returns the wait's number, for its timer. |
| 235 | + pub(crate) fn park_as(&mut self, wait: Wait) -> u64 { |
| 236 | + self.wait_gen += 1; |
| 237 | + self.wait = wait; |
| 238 | + self.wait_gen |
| 239 | + } |
| 240 | + |
| 241 | + fn deadline(&self) -> Option<u64> { |
| 242 | + match self.wait { |
| 243 | + Wait::Receive { |
| 244 | + deadline: Some(d), .. |
| 245 | + } |
| 246 | + | Wait::Sleep { deadline: d } => Some(d), |
| 247 | + _ => None, |
| 248 | + } |
| 249 | + } |
| 202 | 250 | } |
| 203 | 251 | |
| 204 | | −struct Slot { |
| 252 | +/// An actor's shared half. |
| 253 | +pub(crate) struct Cell { |
| 205 | 254 | actor: *mut Actor, |
| 206 | | − /// `None` while the fiber is running. |
| 207 | | − fiber: Option<Fiber>, |
| 208 | | − proc: Proc, |
| 255 | + /// Set when the actor exits; read by the actor at its safe points. |
| 256 | + kill: AtomicBool, |
| 257 | + proc: Mutex<Proc>, |
| 209 | 258 | } |
| 210 | 259 | |
| 260 | +// SAFETY: `actor` is dereferenced only by the thread running the actor |
| 261 | +// (and freed after its fiber returned); the rest is atomic or locked. |
| 262 | +unsafe impl Send for Cell {} |
| 263 | +// SAFETY: as above. |
| 264 | +unsafe impl Sync for Cell {} |
| 265 | + |
| 266 | +/// What the control lock guards: the clock's timers, sockets, blocking |
| 267 | +/// calls, and the end of the program. |
| 211 | 268 | #[derive(Default)] |
| 212 | | −pub(crate) struct Sched { |
| 213 | | − actors: HashMap<i64, Slot>, |
| 214 | | − run_queue: VecDeque<i64>, |
| 215 | | − next_pid: i64, |
| 216 | | − pub(crate) next_tag: i64, |
| 217 | | − pub(crate) clock: u64, |
| 218 | | − /// (watched, watcher, tag) |
| 219 | | − pub(crate) monitors: Vec<(i64, i64, i64)>, |
| 220 | | − root: i64, |
| 269 | +struct Control { |
| 270 | + /// (deadline, pid, wait number), soonest first, then by pid (due |
| 271 | + /// actors wake in pid order, as in the interpreter). |
| 272 | + timers: BinaryHeap<Reverse<(u64, i64, u64)>>, |
| 221 | 273 | outcome: Option<Exit>, |
| 222 | 274 | /// Calls running on the blocking pool. |
| 223 | | − pub(crate) blocking: usize, |
| 275 | + blocking: usize, |
| 224 | 276 | /// The reactor for sockets. Taken out while a thread waits on it. |
| 225 | 277 | poll: Option<mio::Poll>, |
| 226 | 278 | registry: Option<mio::Registry>, |
| 227 | | − /// Wakes the reactor when a blocking call finishes. |
| 228 | | − pub(crate) waker: Option<std::sync::Arc<mio::Waker>>, |
| 229 | 279 | next_token: usize, |
| 230 | 280 | /// Actors parked on a socket, by its token. |
| 231 | | − pub(crate) io_waiters: HashMap<mio::Token, i64>, |
| 281 | + io_waiters: HashMap<mio::Token, i64>, |
| 232 | 282 | /// Sockets that became ready while no actor waited on them. Events are |
| 233 | 283 | /// edge-triggered, and another thread may poll between an actor's |
| 234 | 284 | /// `WouldBlock` and its parking: the actor then retries instead. |
| 235 | | − pub(crate) io_ready: HashSet<mio::Token>, |
| 236 | | − /// Actors running now (one per busy thread). |
| 237 | | − running: usize, |
| 238 | | − /// A thread is waiting for the blocking pool, sockets or the clock. |
| 239 | | − idling: bool, |
| 240 | | − /// Every actor is gone: the threads stop. |
| 241 | | − finished: bool, |
| 285 | + io_ready: HashSet<mio::Token>, |
| 242 | 286 | /// Stacks of `PROGRAM_STACK_SIZE` whose fibers finished. |
| 243 | | − stacks: Vec<DefaultStack>, |
| 244 | | − /// Work was queued: wake the waiting threads when the lock is released. |
| 245 | | − notify: bool, |
| 287 | + stacks: Vec<Stack>, |
| 246 | 288 | } |
| 247 | 289 | |
| 248 | | −// SAFETY: the raw pointers in `Slot` are only dereferenced under the |
| 249 | | −// scheduler lock, or by the one thread running that actor; `Value`s in |
| 250 | | −// mailboxes are made thread-safe by `send::transfer`. |
| 251 | | −unsafe impl Send for Sched {} |
| 252 | | − |
| 253 | | −/// The scheduler state shared by the threads. |
| 290 | +/// The scheduler, shared by its threads. |
| 291 | +/// |
| 292 | +/// **Lock order:** the actor table, then `control`, then an actor's |
| 293 | +/// `proc` lock, then the sleepers' lock. A thread holding one never takes |
| 294 | +/// an earlier one, and holds at most one actor lock. |
| 254 | 295 | pub(crate) struct Shared { |
| 255 | | − state: Mutex<Sched>, |
| 256 | | − /// Signalled when work is queued, a thread stops idling, or the last |
| 257 | | − /// actor finished. |
| 258 | | − work: Condvar, |
| 296 | + actors: RwLock<HashMap<i64, Arc<Cell>>>, |
| 297 | + next_pid: AtomicI64, |
| 298 | + next_tag: AtomicI64, |
| 299 | + /// Virtual time in milliseconds (written under `control`). |
| 300 | + clock: AtomicU64, |
| 301 | + root: AtomicI64, |
| 302 | + control: Mutex<Control>, |
| 303 | + /// Run queues: one per thread (in `LOCAL`), plus this one for actors |
| 304 | + /// queued by other threads (the first actor). |
| 305 | + injector: Injector<i64>, |
| 306 | + stealers: OnceLock<Vec<Stealer<i64>>>, |
| 307 | + /// Actors in a run queue, and actors running. |
| 308 | + pending: AtomicUsize, |
| 309 | + running: AtomicUsize, |
| 310 | + /// A thread is waiting for the blocking pool, sockets or the clock. |
| 311 | + idling: AtomicBool, |
| 312 | + /// Every actor is gone: the threads stop. |
| 313 | + finished: AtomicBool, |
| 314 | + sleepers: Sleepers, |
| 315 | + /// Interrupts the idle thread's wait on the reactor. |
| 316 | + waker: OnceLock<Arc<mio::Waker>>, |
| 317 | + io_waiting: AtomicUsize, |
| 318 | + blocking: AtomicUsize, |
| 259 | 319 | } |
| 260 | 320 | |
| 261 | | −/// The locked scheduler. Releasing it wakes the waiting threads if work |
| 262 | | −/// was queued meanwhile. |
| 263 | | −pub(crate) struct Locked<'a> { |
| 264 | | − guard: Option<MutexGuard<'a, Sched>>, |
| 265 | | − work: &'a Condvar, |
| 321 | +thread_local! { |
| 322 | + /// This scheduler thread's run queue, and its scheduler's address. |
| 323 | + /// Only touched briefly (never held across a fiber switch). |
| 324 | + static LOCAL: RefCell<Option<(usize, Worker<i64>)>> = const { RefCell::new(None) }; |
| 266 | 325 | } |
| 267 | 326 | |
| 268 | | −impl Shared { |
| 269 | | − fn new() -> Shared { |
| 270 | | − Shared { |
| 271 | | − state: Mutex::new(Sched::default()), |
| 272 | | − work: Condvar::new(), |
| 273 | | − } |
| 274 | | − } |
| 275 | | − |
| 276 | | − pub(crate) fn lock(&self) -> Locked<'_> { |
| 277 | | − Locked { |
| 278 | | − guard: Some(self.state.lock().expect("tilrt: scheduler poisoned")), |
| 279 | | − work: &self.work, |
| 327 | +/// Push to this thread's queue if it is one of `sched`'s threads. |
| 328 | +#[inline(never)] |
| 329 | +fn push_local(sched: &Shared, pid: i64) -> bool { |
| 330 | + LOCAL.with(|l| match &*l.borrow() { |
| 331 | + Some((owner, w)) if *owner == sched as *const Shared as usize => { |
| 332 | + w.push(pid); |
| 333 | + true |
| 280 | 334 | } |
| 281 | | − } |
| 282 | | −} |
| 283 | | − |
| 284 | | −impl Locked<'_> { |
| 285 | | − /// Release the lock until another thread signals work. |
| 286 | | − fn wait(mut self) -> Self { |
| 287 | | − let guard = self.guard.take().expect("locked"); |
| 288 | | − let guard = self.work.wait(guard).expect("tilrt: scheduler poisoned"); |
| 289 | | − self.guard = Some(guard); |
| 290 | | − self |
| 291 | | − } |
| 292 | | −} |
| 293 | | − |
| 294 | | −impl std::ops::Deref for Locked<'_> { |
| 295 | | − type Target = Sched; |
| 296 | | − fn deref(&self) -> &Sched { |
| 297 | | − self.guard.as_ref().expect("locked") |
| 298 | | − } |
| 335 | + _ => false, |
| 336 | + }) |
| 299 | 337 | } |
| 300 | 338 | |
| 301 | | −impl std::ops::DerefMut for Locked<'_> { |
| 302 | | − fn deref_mut(&mut self) -> &mut Sched { |
| 303 | | − self.guard.as_mut().expect("locked") |
| 304 | | − } |
| 305 | | −} |
| 306 | | − |
| 307 | | −impl Drop for Locked<'_> { |
| 308 | | − fn drop(&mut self) { |
| 309 | | − if let Some(guard) = &mut self.guard |
| 310 | | − && std::mem::take(&mut guard.notify) |
| 311 | | − { |
| 312 | | − self.work.notify_all(); |
| 313 | | − } |
| 314 | | − } |
| 339 | +#[inline(never)] |
| 340 | +fn pop_local() -> Option<i64> { |
| 341 | + LOCAL.with(|l| l.borrow().as_ref().and_then(|(_, w)| w.pop())) |
| 315 | 342 | } |
| 316 | 343 | |
| 317 | 344 | /// # Safety |
| @@ -362,70 +389,163 @@ pub(crate) unsafe fn this<'a>(ctx: *mut Ctx) -> (&'a Actor, &'a Shared) { |
| 362 | 389 | } |
| 363 | 390 | } |
| 364 | 391 | |
| 365 | | −impl Sched { |
| 366 | | − pub(crate) fn tag(&mut self) -> i64 { |
| 367 | | − self.next_tag += 1; |
| 368 | | − self.next_tag |
| 392 | +impl Shared { |
| 393 | + fn new() -> Shared { |
| 394 | + Shared { |
| 395 | + actors: RwLock::new(HashMap::new()), |
| 396 | + next_pid: AtomicI64::new(0), |
| 397 | + next_tag: AtomicI64::new(0), |
| 398 | + clock: AtomicU64::new(0), |
| 399 | + root: AtomicI64::new(-1), |
| 400 | + control: Mutex::new(Control::default()), |
| 401 | + injector: Injector::new(), |
| 402 | + stealers: OnceLock::new(), |
| 403 | + pending: AtomicUsize::new(0), |
| 404 | + running: AtomicUsize::new(0), |
| 405 | + idling: AtomicBool::new(false), |
| 406 | + finished: AtomicBool::new(false), |
| 407 | + sleepers: Sleepers::new(), |
| 408 | + waker: OnceLock::new(), |
| 409 | + io_waiting: AtomicUsize::new(0), |
| 410 | + blocking: AtomicUsize::new(0), |
| 411 | + } |
| 369 | 412 | } |
| 370 | 413 | |
| 371 | | − /// The OTP state of actor `pid`, if its fiber has not finished. |
| 372 | | − pub(crate) fn proc(&mut self, pid: i64) -> Option<&mut Proc> { |
| 373 | | − self.actors.get_mut(&pid).map(|slot| &mut slot.proc) |
| 414 | + fn control(&self) -> MutexGuard<'_, Control> { |
| 415 | + self.control.lock().expect("tilrt: scheduler poisoned") |
| 374 | 416 | } |
| 375 | 417 | |
| 376 | | − /// The OTP state of actor `pid`, if it is alive (not exited). |
| 377 | | − pub(crate) fn alive(&mut self, pid: i64) -> Option<&mut Proc> { |
| 378 | | − self.proc(pid).filter(|p| !p.dead) |
| 418 | + fn cell(&self, pid: i64) -> Option<Arc<Cell>> { |
| 419 | + self.actors |
| 420 | + .read() |
| 421 | + .expect("tilrt: scheduler poisoned") |
| 422 | + .get(&pid) |
| 423 | + .cloned() |
| 379 | 424 | } |
| 380 | 425 | |
| 381 | | − /// Make a parked actor runnable; its operation returns `wake`. If its |
| 382 | | − /// fiber is still running (on its way to suspending), the thread |
| 383 | | − /// running it queues it. |
| 384 | | − pub(crate) fn wake(&mut self, pid: i64, wake: Value) { |
| 385 | | − let Some(slot) = self.actors.get_mut(&pid) else { |
| 386 | | − return; |
| 387 | | − }; |
| 388 | | − slot.proc.wait = Wait::Ready; |
| 389 | | − slot.proc.wake = wake; |
| 390 | | − if slot.fiber.is_some() { |
| 391 | | − self.run_queue.push_back(pid); |
| 392 | | − self.notify = true; |
| 426 | + pub(crate) fn tag(&self) -> i64 { |
| 427 | + self.next_tag.fetch_add(1, Ordering::Relaxed) + 1 |
| 428 | + } |
| 429 | + |
| 430 | + /// The virtual clock, in milliseconds. |
| 431 | + pub(crate) fn clock(&self) -> u64 { |
| 432 | + self.clock.load(Ordering::Acquire) |
| 433 | + } |
| 434 | + |
| 435 | + /// Run `f` on the OTP state of `pid`, if its fiber has not finished. |
| 436 | + pub(crate) fn with_proc<R>(&self, pid: i64, f: impl FnOnce(&mut Proc) -> R) -> Option<R> { |
| 437 | + let cell = self.cell(pid)?; |
| 438 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 439 | + Some(f(&mut p)) |
| 440 | + } |
| 441 | + |
| 442 | + /// Run `f` on the OTP state of `pid`, if it is alive (not exited). |
| 443 | + pub(crate) fn with_alive<R>(&self, pid: i64, f: impl FnOnce(&mut Proc) -> R) -> Option<R> { |
| 444 | + let cell = self.cell(pid)?; |
| 445 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 446 | + if p.dead { |
| 447 | + return None; |
| 448 | + } |
| 449 | + Some(f(&mut p)) |
| 450 | + } |
| 451 | + |
| 452 | + /// Whether `pid` is alive (not exited). |
| 453 | + pub(crate) fn exists(&self, pid: i64) -> bool { |
| 454 | + self.with_alive(pid, |_| ()).is_some() |
| 455 | + } |
| 456 | + |
| 457 | + /// Queue `pid`, which [`Proc::wake`] (or a new actor) made runnable. |
| 458 | + pub(crate) fn schedule(&self, pid: i64) { |
| 459 | + self.push(pid); |
| 460 | + self.nudge_idler(); |
| 461 | + } |
| 462 | + |
| 463 | + fn push(&self, pid: i64) { |
| 464 | + self.enqueue(pid); |
| 465 | + self.sleepers.notify(false); |
| 466 | + } |
| 467 | + |
| 468 | + fn enqueue(&self, pid: i64) { |
| 469 | + self.pending.fetch_add(1, Ordering::SeqCst); |
| 470 | + if !push_local(self, pid) { |
| 471 | + self.injector.push(pid); |
| 393 | 472 | } |
| 394 | 473 | } |
| 395 | 474 | |
| 396 | | − /// Wake `pid` unless it is runnable or in a blocking call. |
| 397 | | − fn interrupt(&mut self, pid: i64) { |
| 398 | | − if self |
| 399 | | − .proc(pid) |
| 400 | | − .is_some_and(|p| p.wait != Wait::Ready && p.wait != Wait::Blocking) |
| 475 | + /// The idle thread may be waiting on the reactor for something that |
| 476 | + /// no longer matters (work arrived, a sooner timer, the end): wake it. |
| 477 | + fn nudge_idler(&self) { |
| 478 | + if self.idling.load(Ordering::SeqCst) |
| 479 | + && let Some(w) = self.waker.get() |
| 401 | 480 | { |
| 402 | | − self.wake(pid, UNIT); |
| 481 | + let _ = w.wake(); |
| 403 | 482 | } |
| 404 | 483 | } |
| 405 | 484 | |
| 406 | | − pub(crate) fn io_token(&mut self) -> mio::Token { |
| 407 | | − self.next_token += 1; |
| 408 | | − mio::Token(self.next_token) |
| 485 | + /// Wake `pid` with a timeout at `deadline` if it is still in wait |
| 486 | + /// number `generation` then. |
| 487 | + pub(crate) fn add_timer(&self, deadline: u64, pid: i64, generation: u64) { |
| 488 | + self.control() |
| 489 | + .timers |
| 490 | + .push(Reverse((deadline, pid, generation))); |
| 491 | + self.nudge_idler(); |
| 409 | 492 | } |
| 410 | 493 | |
| 411 | | − pub(crate) fn registry(&self) -> &mio::Registry { |
| 412 | | − self.registry |
| 494 | + pub(crate) fn io_token(&self) -> mio::Token { |
| 495 | + let mut c = self.control(); |
| 496 | + c.next_token += 1; |
| 497 | + mio::Token(c.next_token) |
| 498 | + } |
| 499 | + |
| 500 | + /// Run `f` with the reactor's registry. |
| 501 | + pub(crate) fn with_registry<R>(&self, f: impl FnOnce(&mio::Registry) -> R) -> R { |
| 502 | + let c = self.control(); |
| 503 | + f(c.registry |
| 413 | 504 | .as_ref() |
| 414 | | − .expect("tilrt: the reactor starts with the scheduler") |
| 505 | + .expect("tilrt: the reactor starts with the scheduler")) |
| 415 | 506 | } |
| 416 | 507 | |
| 417 | | − /// Whether `pid` is alive (not exited). |
| 418 | | − pub(crate) fn exists(&mut self, pid: i64) -> bool { |
| 419 | | − self.alive(pid).is_some() |
| 508 | + /// Park `pid` (its wait already `Io`) on socket `token`, unless the |
| 509 | + /// socket became ready meanwhile: then returns false, and the caller |
| 510 | + /// retries instead of parking. |
| 511 | + pub(crate) fn io_wait(&self, token: mio::Token, pid: i64) -> bool { |
| 512 | + let mut c = self.control(); |
| 513 | + if c.io_ready.remove(&token) { |
| 514 | + return false; |
| 515 | + } |
| 516 | + if c.io_waiters.insert(token, pid).is_none() { |
| 517 | + self.io_waiting.fetch_add(1, Ordering::SeqCst); |
| 518 | + } |
| 519 | + true |
| 420 | 520 | } |
| 421 | 521 | |
| 422 | | − /// Mark `pid` as exiting, so it unwinds at its next safe point. |
| 423 | | − fn request_kill(&mut self, pid: i64) { |
| 424 | | − if let Some(slot) = self.actors.get(&pid) { |
| 425 | | − // SAFETY: slots only hold live actors. |
| 426 | | − unsafe { (*slot.actor).kill_requested.store(true, Ordering::Release) }; |
| 522 | + /// Forget `pid`'s wait on `token` (after waking, or being stopped). |
| 523 | + pub(crate) fn io_unwait(&self, token: mio::Token) { |
| 524 | + let mut c = self.control(); |
| 525 | + if c.io_waiters.remove(&token).is_some() { |
| 526 | + self.io_waiting.fetch_sub(1, Ordering::SeqCst); |
| 427 | 527 | } |
| 428 | 528 | } |
| 529 | + |
| 530 | + /// A socket was closed: forget its pending readiness. |
| 531 | + pub(crate) fn io_closed(&self, token: mio::Token) { |
| 532 | + self.control().io_ready.remove(&token); |
| 533 | + } |
| 534 | + |
| 535 | + /// A blocking call starts: returns the waker it signals when done. |
| 536 | + pub(crate) fn blocking_started(&self) -> Arc<mio::Waker> { |
| 537 | + self.control().blocking += 1; |
| 538 | + self.blocking.fetch_add(1, Ordering::SeqCst); |
| 539 | + self.waker |
| 540 | + .get() |
| 541 | + .expect("tilrt: the reactor starts with the scheduler") |
| 542 | + .clone() |
| 543 | + } |
| 544 | + |
| 545 | + /// An actor runs or is queued. |
| 546 | + fn busy(&self) -> bool { |
| 547 | + self.running.load(Ordering::SeqCst) > 0 || self.pending.load(Ordering::SeqCst) > 0 |
| 548 | + } |
| 429 | 549 | } |
| 430 | 550 | |
| 431 | 551 | /// How a new actor is tied to the one spawning it. |
| @@ -446,10 +566,16 @@ fn spawn_actor( |
| 446 | 566 | parent: Option<i64>, |
| 447 | 567 | tie: Tie, |
| 448 | 568 | ) -> (i64, Option<i64>) { |
| 569 | + let pid = sched.next_pid.fetch_add(1, Ordering::Relaxed); |
| 449 | 570 | let link = parent.filter(|_| tie == Tie::Link); |
| 450 | | − let mut s = sched.lock(); |
| 451 | | − let pid = s.next_pid; |
| 452 | | − s.next_pid += 1; |
| 571 | + let monitor = parent |
| 572 | + .filter(|_| tie == Tie::Monitor) |
| 573 | + .map(|watcher| (watcher, sched.tag())); |
| 574 | + let pooled = (stack_size == PROGRAM_STACK_SIZE) |
| 575 | + .then(|| sched.control().stacks.pop()) |
| 576 | + .flatten(); |
| 577 | + let stack = pooled |
| 578 | + .unwrap_or_else(|| Stack::new(stack_size).expect("tilrt: cannot allocate actor stack")); |
| 453 | 579 | let a = Box::into_raw(Box::new(Actor { |
| 454 | 580 | ctx: Ctx { |
| 455 | 581 | yielding: YIELD_NONE, |
| @@ -462,20 +588,12 @@ fn spawn_actor( |
| 462 | 588 | }, |
| 463 | 589 | pid, |
| 464 | 590 | next_marker: 0, |
| 465 | | − kill_requested: AtomicBool::new(false), |
| 466 | 591 | drops: DropStack::default(), |
| 467 | 592 | yielder: std::ptr::null(), |
| 468 | 593 | handler: std::ptr::null(), |
| 469 | 594 | sched, |
| 595 | + cell: std::ptr::null(), |
| 470 | 596 | })); |
| 471 | | − // SAFETY: `a` is a fresh allocation; `rt` points back at it. |
| 472 | | − unsafe { (*a).ctx.rt = a.cast() }; |
| 473 | | − let pooled = (stack_size == PROGRAM_STACK_SIZE) |
| 474 | | − .then(|| s.stacks.pop()) |
| 475 | | − .flatten(); |
| 476 | | − let stack = pooled.unwrap_or_else(|| { |
| 477 | | − DefaultStack::new(stack_size).expect("tilrt: cannot allocate actor stack") |
| 478 | | − }); |
| 479 | 597 | let fiber = Coroutine::with_stack(stack, move |yielder: &Yielder<(), ()>, ()| { |
| 480 | 598 | // SAFETY: the actor outlives its fiber (freed only after Return). |
| 481 | 599 | unsafe { |
| @@ -483,39 +601,51 @@ fn spawn_actor( |
| 483 | 601 | run_body(a, body); |
| 484 | 602 | } |
| 485 | 603 | }); |
| 486 | | − s.actors.insert( |
| 487 | | − pid, |
| 488 | | − Slot { |
| 489 | | − actor: a, |
| 490 | | − fiber: Some(Fiber(fiber, stack_size)), |
| 491 | | − proc: Proc { |
| 492 | | − mailbox: Mailbox::default(), |
| 493 | | − wait: Wait::Ready, |
| 494 | | − wake: UNIT, |
| 495 | | − links: link.into_iter().collect(), |
| 496 | | − trap: false, |
| 497 | | − exits_tag: None, |
| 498 | | − waiting_tags: Vec::new(), |
| 499 | | − waiting_any: false, |
| 500 | | − dead: false, |
| 501 | | − }, |
| 502 | | − }, |
| 503 | | − ); |
| 504 | | − if let Some(parent) = link.and_then(|p| s.proc(p)) { |
| 505 | | − parent.links.push(pid); |
| 604 | + let mut run = RunState::new(Fiber(fiber, stack_size)); |
| 605 | + run.queue_new(); |
| 606 | + let cell = Arc::new(Cell { |
| 607 | + actor: a, |
| 608 | + kill: AtomicBool::new(false), |
| 609 | + proc: Mutex::new(Proc { |
| 610 | + mailbox: Mailbox::default(), |
| 611 | + wait: Wait::Ready, |
| 612 | + wake: UNIT, |
| 613 | + links: link.into_iter().collect(), |
| 614 | + monitors: monitor.into_iter().collect(), |
| 615 | + trap: false, |
| 616 | + exits_tag: None, |
| 617 | + waiting_tags: Vec::new(), |
| 618 | + waiting_any: false, |
| 619 | + wait_gen: 0, |
| 620 | + dead: false, |
| 621 | + run, |
| 622 | + }), |
| 623 | + }); |
| 624 | + // SAFETY: `a` is a fresh allocation; `rt` points back at it, `cell` |
| 625 | + // at its shared half (kept alive by the table until it finishes). |
| 626 | + unsafe { |
| 627 | + (*a).ctx.rt = a.cast(); |
| 628 | + (*a).cell = Arc::as_ptr(&cell); |
| 506 | 629 | } |
| 507 | | − let monitor = match (parent, tie) { |
| 508 | | − (Some(watcher), Tie::Monitor) => { |
| 509 | | − let tag = s.tag(); |
| 510 | | − s.monitors.push((pid, watcher, tag)); |
| 511 | | − Some(tag) |
| 512 | | − } |
| 513 | | − _ => None, |
| 514 | | − }; |
| 515 | | − s.run_queue.push_back(pid); |
| 516 | | − s.notify = true; |
| 630 | + sched |
| 631 | + .actors |
| 632 | + .write() |
| 633 | + .expect("tilrt: scheduler poisoned") |
| 634 | + .insert(pid, cell); |
| 517 | 635 | LIVE_ACTORS.fetch_add(1, Ordering::Relaxed); |
| 518 | | − (pid, monitor) |
| 636 | + // The parent links once the child exists (so the parent's exit always |
| 637 | + // reaches it), and before it can run. |
| 638 | + let orphan = link.is_some_and(|p| { |
| 639 | + sched |
| 640 | + .with_alive(p, |parent| parent.links.push(pid)) |
| 641 | + .is_none() |
| 642 | + }); |
| 643 | + sched.schedule(pid); |
| 644 | + if orphan { |
| 645 | + // Linked to an actor that already exited: stop at once. |
| 646 | + exit_actor(sched, pid, Exit::Killed); |
| 647 | + } |
| 648 | + (pid, monitor.map(|(_, tag)| tag)) |
| 519 | 649 | } |
| 520 | 650 | |
| 521 | 651 | /// Spawn a compiled program's actor running `body` (consumed), tied to |
| @@ -579,14 +709,14 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 579 | 709 | let sched = &*(*a).sched; |
| 580 | 710 | exit_actor(sched, (*a).pid, reason); |
| 581 | 711 | // Release what the actor still owns. Nobody delivers to it now. |
| 582 | | − let (mut mailbox, wake) = { |
| 583 | | − let mut s = sched.lock(); |
| 584 | | − let p = s.proc((*a).pid).expect("tilrt: running actor vanished"); |
| 585 | | − ( |
| 586 | | − std::mem::take(&mut p.mailbox), |
| 587 | | − std::mem::replace(&mut p.wake, UNIT), |
| 588 | | − ) |
| 589 | | − }; |
| 712 | + let (mut mailbox, wake) = sched |
| 713 | + .with_proc((*a).pid, |p| { |
| 714 | + ( |
| 715 | + std::mem::take(&mut p.mailbox), |
| 716 | + std::mem::replace(&mut p.wake, UNIT), |
| 717 | + ) |
| 718 | + }) |
| 719 | + .expect("tilrt: running actor vanished"); |
| 590 | 720 | for message in mailbox.drain() { |
| 591 | 721 | drop_value(ctx, message); |
| 592 | 722 | } |
| @@ -597,43 +727,51 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 597 | 727 | /// Stop `pid` (logically): record its exit, notify monitors, propagate |
| 598 | 728 | /// through links, and make sure its fiber unwinds. |
| 599 | 729 | pub(crate) fn exit_actor(sched: &Shared, pid: i64, reason: Exit) { |
| 600 | | − let (links, fired) = { |
| 601 | | − let mut s = sched.lock(); |
| 602 | | − let root = s.root; |
| 603 | | − let Some(p) = s.alive(pid) else { |
| 730 | + let Some(cell) = sched.cell(pid) else { |
| 731 | + return; |
| 732 | + }; |
| 733 | + let (links, monitors, wake) = { |
| 734 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 735 | + if p.dead { |
| 604 | 736 | return; |
| 605 | | − }; |
| 606 | | − p.dead = true; |
| 607 | | − let links = std::mem::take(&mut p.links); |
| 608 | | − if pid == root && s.outcome.is_none() { |
| 609 | | − s.outcome = Some(reason.clone()); |
| 610 | | − } |
| 611 | | − if let Exit::Crashed(m) = &reason { |
| 612 | | − let program = PROGRAM_MODE.load(Ordering::Relaxed); |
| 613 | | − if !(program && pid == root) { |
| 614 | | − let prefix = if program { "" } else { "tilrt: " }; |
| 615 | | − eprintln!("{prefix}actor {pid} crashed: {m}"); |
| 616 | | − } |
| 617 | 737 | } |
| 738 | + p.dead = true; |
| 618 | 739 | // Its fiber unwinds the next time it runs (after a blocking call |
| 619 | 740 | // returns: that call still reads the actor's values). |
| 620 | | − s.request_kill(pid); |
| 621 | | − s.interrupt(pid); |
| 622 | | − let (fired, kept) = s.monitors.drain(..).partition(|(w, _, _)| *w == pid); |
| 623 | | − s.monitors = kept; |
| 624 | | − (links, fired) |
| 741 | + cell.kill.store(true, Ordering::Release); |
| 742 | + ( |
| 743 | + std::mem::take(&mut p.links), |
| 744 | + std::mem::take(&mut p.monitors), |
| 745 | + p.interrupt(), |
| 746 | + ) |
| 625 | 747 | }; |
| 626 | | − for (_, watcher, tag) in fired { |
| 748 | + drop(cell); |
| 749 | + if wake { |
| 750 | + sched.schedule(pid); |
| 751 | + } |
| 752 | + let root = sched.root.load(Ordering::Acquire); |
| 753 | + if pid == root { |
| 754 | + sched |
| 755 | + .control() |
| 756 | + .outcome |
| 757 | + .get_or_insert_with(|| reason.clone()); |
| 758 | + } |
| 759 | + if let Exit::Crashed(m) = &reason { |
| 760 | + let program = PROGRAM_MODE.load(Ordering::Relaxed); |
| 761 | + if !(program && pid == root) { |
| 762 | + let prefix = if program { "" } else { "tilrt: " }; |
| 763 | + eprintln!("{prefix}actor {pid} crashed: {m}"); |
| 764 | + } |
| 765 | + } |
| 766 | + for (watcher, tag) in monitors { |
| 627 | 767 | crate::process::deliver_down(sched, watcher, tag, pid, &reason); |
| 628 | 768 | } |
| 629 | 769 | for linked in links { |
| 630 | | − let trap = { |
| 631 | | − let mut s = sched.lock(); |
| 632 | | − let Some(other) = s.alive(linked) else { |
| 633 | | − continue; |
| 634 | | − }; |
| 770 | + let Some(trap) = sched.with_alive(linked, |other| { |
| 635 | 771 | other.links.retain(|l| *l != pid); |
| 636 | 772 | other.trap |
| 773 | + }) else { |
| 774 | + continue; |
| 637 | 775 | }; |
| 638 | 776 | // As in Erlang: actors that trap exits are told about every exit, |
| 639 | 777 | // normal ones included; others only die of abnormal ones. |
| @@ -645,6 +783,28 @@ pub(crate) fn exit_actor(sched: &Shared, pid: i64, reason: Exit) { |
| 645 | 783 | } |
| 646 | 784 | } |
| 647 | 785 | |
| 786 | +/// `main` stopped: stop every other actor, silently. |
| 787 | +fn stop_all(sched: &Shared) { |
| 788 | + let cells: Vec<(i64, Arc<Cell>)> = sched |
| 789 | + .actors |
| 790 | + .read() |
| 791 | + .expect("tilrt: scheduler poisoned") |
| 792 | + .iter() |
| 793 | + .map(|(pid, cell)| (*pid, cell.clone())) |
| 794 | + .collect(); |
| 795 | + for (pid, cell) in cells { |
| 796 | + cell.kill.store(true, Ordering::Release); |
| 797 | + let wake = { |
| 798 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 799 | + p.dead = true; |
| 800 | + p.interrupt() |
| 801 | + }; |
| 802 | + if wake { |
| 803 | + sched.schedule(pid); |
| 804 | + } |
| 805 | + } |
| 806 | +} |
| 807 | + |
| 648 | 808 | /// The number of scheduler threads: `TILC_THREADS`, or one per core. |
| 649 | 809 | fn thread_count() -> usize { |
| 650 | 810 | std::env::var("TILC_THREADS") |
| @@ -658,153 +818,246 @@ fn thread_count() -> usize { |
| 658 | 818 | /// When the root exits, every other actor is stopped (and unwound). |
| 659 | 819 | /// Returns the root's exit. |
| 660 | 820 | fn run(sched: &Shared, root: i64, threads: usize) -> Exit { |
| 821 | + sched.root.store(root, Ordering::Release); |
| 661 | 822 | { |
| 662 | | − let mut s = sched.lock(); |
| 663 | | − s.root = root; |
| 823 | + let mut c = sched.control(); |
| 664 | 824 | let poll = mio::Poll::new().expect("tilrt: cannot create the reactor"); |
| 665 | | − s.registry = Some( |
| 825 | + c.registry = Some( |
| 666 | 826 | poll.registry() |
| 667 | 827 | .try_clone() |
| 668 | 828 | .expect("tilrt: cannot share the reactor"), |
| 669 | 829 | ); |
| 670 | | − s.waker = Some(std::sync::Arc::new( |
| 671 | | − mio::Waker::new(poll.registry(), WAKER).expect("tilrt: cannot create the waker"), |
| 672 | | − )); |
| 673 | | − s.poll = Some(poll); |
| 830 | + let waker = |
| 831 | + mio::Waker::new(poll.registry(), WAKER).expect("tilrt: cannot create the waker"); |
| 832 | + let _ = sched.waker.set(Arc::new(waker)); |
| 833 | + c.poll = Some(poll); |
| 674 | 834 | } |
| 835 | + // FIFO queues: with one thread, actors run in the order they were |
| 836 | + // queued, as in the interpreter. |
| 837 | + let workers: Vec<Worker<i64>> = (0..threads).map(|_| Worker::new_fifo()).collect(); |
| 838 | + let _ = sched |
| 839 | + .stealers |
| 840 | + .set(workers.iter().map(Worker::stealer).collect()); |
| 675 | 841 | std::thread::scope(|scope| { |
| 676 | | − for i in 1..threads { |
| 842 | + let mut workers = workers.into_iter().enumerate(); |
| 843 | + let (_, first) = workers.next().expect("one thread at least"); |
| 844 | + for (i, w) in workers { |
| 677 | 845 | std::thread::Builder::new() |
| 678 | 846 | .name(format!("tilrt-sched-{i}")) |
| 679 | | − .spawn_scoped(scope, || worker(sched)) |
| 847 | + .spawn_scoped(scope, move || worker(sched, i, w)) |
| 680 | 848 | .expect("tilrt: cannot start a scheduler thread"); |
| 681 | 849 | } |
| 682 | | − worker(sched); |
| 850 | + worker(sched, 0, first); |
| 683 | 851 | }); |
| 684 | | − sched.lock().outcome.take().unwrap_or(Exit::Normal) |
| 852 | + sched.control().outcome.take().unwrap_or(Exit::Normal) |
| 685 | 853 | } |
| 686 | 854 | |
| 687 | | −/// One scheduler thread: run actors from the queue. When no actor can run |
| 688 | | −/// on any thread, one thread waits for blocking calls, sockets or the next |
| 689 | | −/// deadline, as the single-threaded scheduler did. |
| 690 | | −fn worker(sched: &Shared) { |
| 691 | | − let mut s = sched.lock(); |
| 855 | +/// One scheduler thread: run actors from its queue, else from the shared |
| 856 | +/// one, else steal from the others. When no actor runs or is queued |
| 857 | +/// anywhere, one thread idles for everyone (blocking calls, sockets, the |
| 858 | +/// clock); the others sleep. |
| 859 | +fn worker(sched: &Shared, index: usize, queue: Worker<i64>) { |
| 860 | + LOCAL.with(|l| *l.borrow_mut() = Some((sched as *const Shared as usize, queue))); |
| 692 | 861 | loop { |
| 693 | | − if s.finished { |
| 694 | | − return; |
| 862 | + if sched.finished.load(Ordering::SeqCst) { |
| 863 | + break; |
| 695 | 864 | } |
| 696 | | − collect_blocking(&mut s); |
| 697 | | − if !s.io_waiters.is_empty() { |
| 698 | | − poll_io(&mut s); |
| 699 | | − } |
| 700 | | − if let Some(pid) = s.run_queue.pop_front() { |
| 701 | | − s = run_slice(sched, s, pid); |
| 865 | + collect_events(sched); |
| 866 | + if let Some(pid) = find_work(sched, index) { |
| 867 | + run_slice(sched, pid); |
| 702 | 868 | continue; |
| 703 | 869 | } |
| 704 | | − if s.actors.is_empty() { |
| 705 | | − s.finished = true; |
| 706 | | − s.notify = true; |
| 707 | | − return; |
| 870 | + if sched.pending.load(Ordering::SeqCst) > 0 { |
| 871 | + // Queued, but not stealable yet (a push in progress). |
| 872 | + std::thread::yield_now(); |
| 873 | + continue; |
| 708 | 874 | } |
| 709 | | − if s.running > 0 || s.idling { |
| 710 | | − // Another thread will queue work, or idle for everyone. |
| 711 | | − s = s.wait(); |
| 875 | + if sched.running.load(Ordering::SeqCst) > 0 || sched.idling.load(Ordering::SeqCst) { |
| 876 | + sched.sleepers.sleep(|| { |
| 877 | + sched.pending.load(Ordering::SeqCst) == 0 |
| 878 | + && !sched.finished.load(Ordering::SeqCst) |
| 879 | + && (sched.running.load(Ordering::SeqCst) > 0 |
| 880 | + || sched.idling.load(Ordering::SeqCst)) |
| 881 | + }); |
| 712 | 882 | continue; |
| 713 | 883 | } |
| 714 | | − s.idling = true; |
| 715 | | − drop(s); |
| 716 | | − idle(sched); |
| 717 | | − s = sched.lock(); |
| 718 | | − s.idling = false; |
| 719 | | − s.notify = true; |
| 884 | + if sched |
| 885 | + .idling |
| 886 | + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) |
| 887 | + .is_ok() |
| 888 | + { |
| 889 | + idle(sched); |
| 890 | + sched.idling.store(false, Ordering::SeqCst); |
| 891 | + sched.sleepers.notify(true); |
| 892 | + } |
| 720 | 893 | } |
| 894 | + LOCAL.with(|l| l.borrow_mut().take()); |
| 721 | 895 | } |
| 722 | 896 | |
| 723 | | −/// Resume `pid` for one slice, without holding the lock. |
| 724 | | −fn run_slice<'a>(sched: &'a Shared, mut s: Locked<'a>, pid: i64) -> Locked<'a> { |
| 725 | | − let Some(slot) = s.actors.get_mut(&pid) else { |
| 726 | | − return s; |
| 897 | +/// The next actor for thread `index`: its own queue first (FIFO), then |
| 898 | +/// the shared queue, then the other threads' queues. |
| 899 | +fn find_work(sched: &Shared, index: usize) -> Option<i64> { |
| 900 | + if let Some(pid) = pop_local() { |
| 901 | + return Some(pid); |
| 902 | + } |
| 903 | + let stealers = sched.stealers.get().expect("stealers"); |
| 904 | + loop { |
| 905 | + let mut retry = false; |
| 906 | + let from_injector = LOCAL.with(|l| match &*l.borrow() { |
| 907 | + Some((_, w)) => sched.injector.steal_batch_and_pop(w), |
| 908 | + None => Steal::Empty, |
| 909 | + }); |
| 910 | + match from_injector { |
| 911 | + Steal::Success(pid) => return Some(pid), |
| 912 | + Steal::Retry => retry = true, |
| 913 | + Steal::Empty => {} |
| 914 | + } |
| 915 | + for k in 1..stealers.len() { |
| 916 | + let victim = &stealers[(index + k) % stealers.len()]; |
| 917 | + let stolen = LOCAL.with(|l| match &*l.borrow() { |
| 918 | + Some((_, w)) => victim.steal_batch_and_pop(w), |
| 919 | + None => Steal::Empty, |
| 920 | + }); |
| 921 | + match stolen { |
| 922 | + Steal::Success(pid) => return Some(pid), |
| 923 | + Steal::Retry => retry = true, |
| 924 | + Steal::Empty => {} |
| 925 | + } |
| 926 | + } |
| 927 | + if !retry { |
| 928 | + return None; |
| 929 | + } |
| 930 | + } |
| 931 | +} |
| 932 | + |
| 933 | +/// Resume `pid` for one slice. |
| 934 | +fn run_slice(sched: &Shared, pid: i64) { |
| 935 | + // Running before no longer pending: the scheduler never looks idle |
| 936 | + // while an actor is between the two. |
| 937 | + sched.running.fetch_add(1, Ordering::SeqCst); |
| 938 | + sched.pending.fetch_sub(1, Ordering::SeqCst); |
| 939 | + let Some(cell) = sched.cell(pid) else { |
| 940 | + stop_running(sched); |
| 941 | + return; |
| 727 | 942 | }; |
| 728 | | − let Some(mut fiber) = slot.fiber.take() else { |
| 729 | | − return s; |
| 943 | + let fiber = cell.proc.lock().expect("tilrt: actor poisoned").run.start(); |
| 944 | + let Some(mut fiber) = fiber else { |
| 945 | + stop_running(sched); |
| 946 | + return; |
| 730 | 947 | }; |
| 731 | | − let a = slot.actor; |
| 732 | | − s.running += 1; |
| 733 | | − drop(s); |
| 948 | + let a = cell.actor; |
| 734 | 949 | // SAFETY: the actor is live and runs on this thread only. |
| 735 | 950 | unsafe { (*a).ctx.reductions = REDUCTIONS }; |
| 736 | 951 | let result = fiber.0.resume(()); |
| 737 | | − let mut s = sched.lock(); |
| 738 | | − s.running -= 1; |
| 739 | | − if s.running == 0 { |
| 740 | | − s.notify = true; // Someone may have to idle for everyone. |
| 741 | | − } |
| 742 | 952 | match result { |
| 743 | 953 | CoroutineResult::Yield(()) => { |
| 744 | | − let slot = s.actors.get_mut(&pid).expect("tilrt: actor vanished"); |
| 745 | | − slot.fiber = Some(fiber); |
| 746 | | − if slot.proc.wait == Wait::Ready { |
| 747 | | − s.run_queue.push_back(pid); |
| 954 | + let again = { |
| 955 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 956 | + let ready = p.wait == Wait::Ready; |
| 957 | + p.run.stop(fiber, ready) |
| 958 | + }; |
| 959 | + if again { |
| 960 | + // Preempted (or woken while it ran): back into this |
| 961 | + // thread's queue, without waking another thread to steal |
| 962 | + // it. No new work appeared, and moving it would only cost |
| 963 | + // a wake-up and cold caches. |
| 964 | + sched.enqueue(pid); |
| 748 | 965 | } |
| 749 | | − s |
| 750 | 966 | } |
| 751 | 967 | CoroutineResult::Return(()) => { |
| 752 | | − let slot = s.actors.remove(&pid).expect("tilrt: actor vanished"); |
| 753 | | − if fiber.1 == PROGRAM_STACK_SIZE && s.stacks.len() < STACK_POOL { |
| 754 | | − let stack = fiber.0.into_stack(); |
| 755 | | − s.stacks.push(stack); |
| 756 | | − } else { |
| 757 | | − drop(fiber); |
| 968 | + cell.proc |
| 969 | + .lock() |
| 970 | + .expect("tilrt: actor poisoned") |
| 971 | + .run |
| 972 | + .finish(); |
| 973 | + let empty = { |
| 974 | + let mut actors = sched.actors.write().expect("tilrt: scheduler poisoned"); |
| 975 | + actors.remove(&pid); |
| 976 | + actors.is_empty() |
| 977 | + }; |
| 978 | + drop(cell); |
| 979 | + if fiber.1 == PROGRAM_STACK_SIZE { |
| 980 | + let mut c = sched.control(); |
| 981 | + if c.stacks.len() < STACK_POOL { |
| 982 | + c.stacks.push(fiber.0.into_stack()); |
| 983 | + } |
| 758 | 984 | } |
| 759 | 985 | // SAFETY: the fiber has returned; nothing refers to the actor. |
| 760 | | − drop(unsafe { Box::from_raw(slot.actor) }); |
| 986 | + drop(unsafe { Box::from_raw(a) }); |
| 761 | 987 | LIVE_ACTORS.fetch_sub(1, Ordering::Relaxed); |
| 762 | | − if pid == s.root { |
| 763 | | − // `main` stopped: stop everyone else, silently. |
| 764 | | − let others: Vec<i64> = s.actors.keys().copied().collect(); |
| 765 | | − for other in others { |
| 766 | | − if let Some(p) = s.proc(other) { |
| 767 | | − p.dead = true; |
| 768 | | − } |
| 769 | | − s.request_kill(other); |
| 770 | | − s.interrupt(other); |
| 771 | | − } |
| 988 | + if pid == sched.root.load(Ordering::Acquire) { |
| 989 | + stop_all(sched); |
| 990 | + } |
| 991 | + if empty { |
| 992 | + sched.finished.store(true, Ordering::SeqCst); |
| 993 | + sched.sleepers.notify(true); |
| 994 | + sched.nudge_idler(); |
| 772 | 995 | } |
| 773 | | − s.notify = true; |
| 774 | | − s |
| 775 | 996 | } |
| 776 | 997 | } |
| 998 | + stop_running(sched); |
| 999 | +} |
| 1000 | + |
| 1001 | +fn stop_running(sched: &Shared) { |
| 1002 | + if sched.running.fetch_sub(1, Ordering::SeqCst) == 1 |
| 1003 | + && sched.pending.load(Ordering::SeqCst) == 0 |
| 1004 | + { |
| 1005 | + // Nothing runs or is queued: someone may have to idle. |
| 1006 | + sched.sleepers.notify(true); |
| 1007 | + sched.nudge_idler(); |
| 1008 | + } |
| 1009 | +} |
| 1010 | + |
| 1011 | +/// Between slices: collect finished blocking calls and ready sockets, |
| 1012 | +/// without waiting (skipped if another thread is at it). |
| 1013 | +fn collect_events(sched: &Shared) { |
| 1014 | + if sched.blocking.load(Ordering::SeqCst) == 0 && sched.io_waiting.load(Ordering::SeqCst) == 0 { |
| 1015 | + return; |
| 1016 | + } |
| 1017 | + let Ok(mut c) = sched.control.try_lock() else { |
| 1018 | + return; |
| 1019 | + }; |
| 1020 | + collect_blocking(sched, &mut c); |
| 1021 | + if !c.io_waiters.is_empty() |
| 1022 | + && let Some(mut poll) = c.poll.take() |
| 1023 | + { |
| 1024 | + let mut events = mio::Events::with_capacity(256); |
| 1025 | + wait_events(&mut poll, &mut events, Some(std::time::Duration::ZERO)); |
| 1026 | + c.poll = Some(poll); |
| 1027 | + wake_io(sched, &mut c, &events); |
| 1028 | + } |
| 777 | 1029 | } |
| 778 | 1030 | |
| 779 | | −/// Every actor waits: wait for blocking calls, sockets or the clock, or |
| 780 | | −/// detect a deadlock. Called by one thread at a time, without the lock. |
| 1031 | +/// No actor runs or is queued: wait for blocking calls, sockets or the |
| 1032 | +/// clock, or detect a deadlock. Called by one thread at a time. |
| 781 | 1033 | /// |
| 782 | | −/// Each decision is taken under one lock, and the thread stops idling as |
| 783 | | −/// soon as an actor runs or is queued (another thread may have polled the |
| 784 | | −/// reactor meanwhile). Blocking calls signal the reactor when they finish |
| 785 | | −/// (`WAKER`), so the reactor is the only thing waited on. |
| 1034 | +/// Each decision is taken under the control lock, and the thread stops |
| 1035 | +/// idling as soon as an actor runs or is queued. Blocking calls, new |
| 1036 | +/// timers and new work signal the reactor (`WAKER`), so the reactor is the |
| 1037 | +/// only thing waited on. |
| 786 | 1038 | fn idle(sched: &Shared) { |
| 787 | 1039 | let (mut poll, real_time, clock, deadline) = { |
| 788 | | − let mut s = sched.lock(); |
| 789 | | − collect_blocking(&mut s); |
| 790 | | − if s.running > 0 || !s.run_queue.is_empty() { |
| 1040 | + let mut c = sched.control(); |
| 1041 | + collect_blocking(sched, &mut c); |
| 1042 | + if sched.busy() { |
| 791 | 1043 | return; |
| 792 | 1044 | } |
| 793 | | − if s.io_waiters.is_empty() && s.blocking == 0 { |
| 1045 | + if c.io_waiters.is_empty() && c.blocking == 0 { |
| 794 | 1046 | // Only the clock can wake an actor now. |
| 795 | | − if !advance_clock(&mut s) { |
| 796 | | − deadlock(sched, s); |
| 1047 | + if !advance_clock(sched, &mut c) { |
| 1048 | + drop(c); |
| 1049 | + deadlock(sched); |
| 797 | 1050 | } |
| 798 | 1051 | return; |
| 799 | 1052 | } |
| 800 | | − let Some(poll) = s.poll.take() else { |
| 1053 | + let deadline = next_deadline(sched, &mut c); |
| 1054 | + let Some(poll) = c.poll.take() else { |
| 801 | 1055 | return; |
| 802 | 1056 | }; |
| 803 | 1057 | // Real time passes while waiting for sockets, and timers fire when |
| 804 | 1058 | // it reaches their deadline. Waiting only for blocking calls keeps |
| 805 | 1059 | // the clock virtual. |
| 806 | | − let real_time = !s.io_waiters.is_empty(); |
| 807 | | − (poll, real_time, s.clock, next_deadline(&s)) |
| 1060 | + (poll, !c.io_waiters.is_empty(), sched.clock(), deadline) |
| 808 | 1061 | }; |
| 809 | 1062 | let timeout = match deadline { |
| 810 | 1063 | Some(d) if real_time => Some(std::time::Duration::from_millis(d.saturating_sub(clock))), |
| @@ -813,61 +1066,62 @@ fn idle(sched: &Shared) { |
| 813 | 1066 | let start = std::time::Instant::now(); |
| 814 | 1067 | let mut events = mio::Events::with_capacity(256); |
| 815 | 1068 | wait_events(&mut poll, &mut events, timeout); |
| 816 | | − let mut s = sched.lock(); |
| 817 | | − s.poll = Some(poll); |
| 1069 | + let mut c = sched.control(); |
| 1070 | + c.poll = Some(poll); |
| 818 | 1071 | if real_time { |
| 819 | | − s.clock += start.elapsed().as_millis() as u64; |
| 1072 | + sched |
| 1073 | + .clock |
| 1074 | + .fetch_add(start.elapsed().as_millis() as u64, Ordering::AcqRel); |
| 820 | 1075 | } |
| 821 | | − let woke = wake_io(&mut s, &events); |
| 822 | | − collect_blocking(&mut s); |
| 1076 | + let woke = wake_io(sched, &mut c, &events); |
| 1077 | + collect_blocking(sched, &mut c); |
| 823 | 1078 | if real_time |
| 824 | 1079 | && !woke |
| 1080 | + && !sched.busy() |
| 825 | 1081 | && let Some(d) = deadline |
| 826 | | − && s.clock >= d |
| 1082 | + && sched.clock() >= d |
| 827 | 1083 | { |
| 828 | | − advance_clock(&mut s); |
| 1084 | + advance_clock(sched, &mut c); |
| 829 | 1085 | } |
| 830 | 1086 | } |
| 831 | 1087 | |
| 832 | 1088 | /// Nothing can ever run again: crash the root (stopping everyone). |
| 833 | | −fn deadlock(sched: &Shared, s: Locked<'_>) { |
| 834 | | − let root = s.root; |
| 835 | | − let alive: Vec<i64> = s.actors.keys().copied().collect(); |
| 836 | | − drop(s); |
| 1089 | +fn deadlock(sched: &Shared) { |
| 1090 | + let alive: Vec<i64> = sched |
| 1091 | + .actors |
| 1092 | + .read() |
| 1093 | + .expect("tilrt: scheduler poisoned") |
| 1094 | + .keys() |
| 1095 | + .copied() |
| 1096 | + .collect(); |
| 837 | 1097 | exit_actor( |
| 838 | 1098 | sched, |
| 839 | | − root, |
| 1099 | + sched.root.load(Ordering::Acquire), |
| 840 | 1100 | Exit::Crashed("deadlock: every actor is waiting for a message".into()), |
| 841 | 1101 | ); |
| 842 | 1102 | for pid in alive { |
| 843 | 1103 | exit_actor(sched, pid, Exit::Killed); |
| 844 | | − sched.lock().interrupt(pid); |
| 1104 | + let wake = sched.with_proc(pid, |p| p.interrupt()) == Some(true); |
| 1105 | + if wake { |
| 1106 | + sched.schedule(pid); |
| 1107 | + } |
| 845 | 1108 | } |
| 846 | 1109 | } |
| 847 | 1110 | |
| 848 | 1111 | /// Wake the actors whose blocking calls finished. |
| 849 | | −fn collect_blocking(s: &mut Sched) { |
| 850 | | − if s.blocking == 0 { |
| 1112 | +fn collect_blocking(sched: &Shared, c: &mut Control) { |
| 1113 | + if c.blocking == 0 { |
| 851 | 1114 | return; |
| 852 | 1115 | } |
| 853 | 1116 | while let Some(done) = crate::blocking::finished() { |
| 854 | | − s.blocking -= 1; |
| 855 | | − s.wake(done.pid, done.result); |
| 1117 | + c.blocking -= 1; |
| 1118 | + sched.blocking.fetch_sub(1, Ordering::SeqCst); |
| 1119 | + if sched.with_proc(done.pid, |p| p.wake(done.result)) == Some(true) { |
| 1120 | + sched.push(done.pid); |
| 1121 | + } |
| 856 | 1122 | } |
| 857 | 1123 | } |
| 858 | 1124 | |
| 859 | | −/// Wake the actors whose sockets are ready, without waiting. Skipped while |
| 860 | | −/// an idle thread holds the reactor. |
| 861 | | −fn poll_io(s: &mut Sched) { |
| 862 | | − let Some(mut poll) = s.poll.take() else { |
| 863 | | − return; |
| 864 | | − }; |
| 865 | | − let mut events = mio::Events::with_capacity(256); |
| 866 | | − wait_events(&mut poll, &mut events, Some(std::time::Duration::ZERO)); |
| 867 | | − s.poll = Some(poll); |
| 868 | | − wake_io(s, &events); |
| 869 | | −} |
| 870 | | − |
| 871 | 1125 | fn wait_events( |
| 872 | 1126 | poll: &mut mio::Poll, |
| 873 | 1127 | events: &mut mio::Events, |
| @@ -881,59 +1135,73 @@ fn wait_events( |
| 881 | 1135 | } |
| 882 | 1136 | |
| 883 | 1137 | /// Wake the actors parked on `events`; returns whether any woke. |
| 884 | | −fn wake_io(s: &mut Sched, events: &mio::Events) -> bool { |
| 1138 | +fn wake_io(sched: &Shared, c: &mut Control, events: &mio::Events) -> bool { |
| 885 | 1139 | let mut woke = false; |
| 886 | 1140 | for event in events { |
| 887 | 1141 | if event.token() == WAKER { |
| 888 | | − continue; // A blocking call finished: see `collect_blocking`. |
| 1142 | + continue; // Blocking calls, new work: see the callers. |
| 889 | 1143 | } |
| 890 | | − if let Some(pid) = s.io_waiters.remove(&event.token()) { |
| 891 | | − s.wake(pid, UNIT); |
| 1144 | + if let Some(pid) = c.io_waiters.remove(&event.token()) { |
| 1145 | + sched.io_waiting.fetch_sub(1, Ordering::SeqCst); |
| 1146 | + if sched.with_proc(pid, |p| p.wake(UNIT)) == Some(true) { |
| 1147 | + sched.push(pid); |
| 1148 | + } |
| 892 | 1149 | woke = true; |
| 893 | 1150 | } else { |
| 894 | | − s.io_ready.insert(event.token()); |
| 1151 | + c.io_ready.insert(event.token()); |
| 895 | 1152 | } |
| 896 | 1153 | } |
| 897 | 1154 | woke |
| 898 | 1155 | } |
| 899 | 1156 | |
| 900 | | −fn deadline_of(p: &Proc) -> Option<u64> { |
| 901 | | − match p.wait { |
| 902 | | − Wait::Receive { |
| 903 | | − deadline: Some(d), .. |
| 904 | | − } |
| 905 | | − | Wait::Sleep { deadline: d } => Some(d), |
| 906 | | − _ => None, |
| 907 | | − } |
| 1157 | +/// Whether timer `(deadline, pid, generation)` still applies: the actor |
| 1158 | +/// is in that wait, with that deadline. |
| 1159 | +fn timer_live(sched: &Shared, deadline: u64, pid: i64, generation: u64) -> bool { |
| 1160 | + sched |
| 1161 | + .with_proc(pid, |p| { |
| 1162 | + p.wait_gen == generation && p.deadline() == Some(deadline) |
| 1163 | + }) |
| 1164 | + .unwrap_or(false) |
| 908 | 1165 | } |
| 909 | 1166 | |
| 910 | | −fn next_deadline(s: &Sched) -> Option<u64> { |
| 911 | | − s.actors |
| 912 | | − .values() |
| 913 | | − .filter_map(|slot| deadline_of(&slot.proc)) |
| 914 | | − .min() |
| 1167 | +/// The soonest deadline still waited for (dropping timers that no longer |
| 1168 | +/// apply). |
| 1169 | +fn next_deadline(sched: &Shared, c: &mut Control) -> Option<u64> { |
| 1170 | + while let Some(&Reverse((deadline, pid, generation))) = c.timers.peek() { |
| 1171 | + if timer_live(sched, deadline, pid, generation) { |
| 1172 | + return Some(deadline); |
| 1173 | + } |
| 1174 | + c.timers.pop(); |
| 1175 | + } |
| 1176 | + None |
| 915 | 1177 | } |
| 916 | 1178 | |
| 917 | | −/// Jump the virtual clock to the next deadline and wake those actors. |
| 918 | | −fn advance_clock(s: &mut Sched) -> bool { |
| 919 | | − let Some(next) = next_deadline(s) else { |
| 1179 | +/// Jump the virtual clock to the next deadline and wake those actors, in |
| 1180 | +/// pid order. |
| 1181 | +fn advance_clock(sched: &Shared, c: &mut Control) -> bool { |
| 1182 | + let Some(next) = next_deadline(sched, c) else { |
| 920 | 1183 | return false; |
| 921 | 1184 | }; |
| 922 | | − s.clock = s.clock.max(next); |
| 923 | | − let mut due: Vec<i64> = s |
| 924 | | − .actors |
| 925 | | − .iter() |
| 926 | | − .filter(|(_, slot)| deadline_of(&slot.proc) == Some(next)) |
| 927 | | − .map(|(p, _)| *p) |
| 928 | | − .collect(); |
| 929 | | − due.sort(); |
| 930 | | − for pid in due { |
| 931 | | − // A receive that timed out returns `None` (constructor 0). |
| 932 | | − let wake = match s.proc(pid).expect("listed").wait { |
| 933 | | − Wait::Sleep { .. } => UNIT, |
| 934 | | − _ => int(0), |
| 935 | | − }; |
| 936 | | − s.wake(pid, wake); |
| 1185 | + sched.clock.fetch_max(next, Ordering::AcqRel); |
| 1186 | + while let Some(&Reverse((deadline, pid, generation))) = c.timers.peek() { |
| 1187 | + if deadline != next { |
| 1188 | + break; |
| 1189 | + } |
| 1190 | + c.timers.pop(); |
| 1191 | + let woke = sched.with_proc(pid, |p| { |
| 1192 | + if p.wait_gen != generation || p.deadline() != Some(deadline) { |
| 1193 | + return false; |
| 1194 | + } |
| 1195 | + // A receive that timed out returns `None` (constructor 0). |
| 1196 | + let value = match p.wait { |
| 1197 | + Wait::Sleep { .. } => UNIT, |
| 1198 | + _ => int(0), |
| 1199 | + }; |
| 1200 | + p.wake(value) |
| 1201 | + }); |
| 1202 | + if woke == Some(true) { |
| 1203 | + sched.push(pid); |
| 1204 | + } |
| 937 | 1205 | } |
| 938 | 1206 | true |
| 939 | 1207 | } |
| @@ -970,9 +1238,9 @@ pub(crate) unsafe fn preempt_root(ctx: *mut Ctx) { |
| 970 | 1238 | } |
| 971 | 1239 | } |
| 972 | 1240 | |
| 973 | | −/// Park the running actor until it is woken (its `wait` must be set, |
| 974 | | −/// under the lock, before calling); returns the wake value, or unit with |
| 975 | | −/// `yielding = KILL` if it exited meanwhile. |
| 1241 | +/// Park the running actor until it is woken (its `wait` must be set |
| 1242 | +/// before calling); returns the wake value, or unit with `yielding = KILL` |
| 1243 | +/// if it exited meanwhile. |
| 976 | 1244 | /// |
| 977 | 1245 | /// # Safety |
| 978 | 1246 | /// `ctx` must be the running actor's context. |
| @@ -981,11 +1249,9 @@ pub(crate) unsafe fn park(ctx: *mut Ctx) -> Value { |
| 981 | 1249 | unsafe { |
| 982 | 1250 | tl_preempt(ctx); |
| 983 | 1251 | let (a, sched) = this(ctx); |
| 984 | | − let wake = { |
| 985 | | − let mut s = sched.lock(); |
| 986 | | − let p = s.proc(a.pid).expect("tilrt: running actor vanished"); |
| 987 | | − std::mem::replace(&mut p.wake, UNIT) |
| 988 | | − }; |
| 1252 | + let wake = sched |
| 1253 | + .with_proc(a.pid, |p| std::mem::replace(&mut p.wake, UNIT)) |
| 1254 | + .expect("tilrt: running actor vanished"); |
| 989 | 1255 | if (*ctx).yielding != YIELD_NONE { |
| 990 | 1256 | drop_value(ctx, wake); |
| 991 | 1257 | return UNIT; |