| @@ -0,0 +1,649 @@ |
| 1 | +//! An actor's OTP state ([`Proc`]): its mailbox, what it waits for, its |
| 2 | +//! links and monitors. Other actors, timers and kills change it under the |
| 3 | +//! actor's lock (ADR 0004, Revision 2), each through one method here, so |
| 4 | +//! that loom models check the code the scheduler runs |
| 5 | +//! (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt --release --lib otp`). |
| 6 | +//! |
| 7 | +//! `Proc` is generic in the values it holds and in the fiber: the runtime |
| 8 | +//! uses `Proc<Value, Fiber>`, the models plain data. Taking the lock is the |
| 9 | +//! caller's job. |
| 10 | + |
| 11 | +use std::collections::VecDeque; |
| 12 | + |
| 13 | +use crate::handoff::RunState; |
| 14 | +use crate::sched::{IdHasher, IdMap}; |
| 15 | + |
| 16 | +/// What parked operations return, made under the lock. |
| 17 | +pub(crate) trait Answer: Sized { |
| 18 | + /// A received message: `Some(message)`, or `Some((tag, message))` |
| 19 | + /// for `receive_any`. |
| 20 | + fn received(message: Self, tag: Option<i64>) -> Self; |
| 21 | + /// `None`: no message before the timeout. |
| 22 | + fn timed_out() -> Self; |
| 23 | + /// `()`: a sleep ended, a socket is ready, or the wait was interrupted. |
| 24 | + fn unit() -> Self; |
| 25 | +} |
| 26 | + |
| 27 | +#[derive(Clone, Copy, Debug, PartialEq)] |
| 28 | +pub(crate) enum Wait { |
| 29 | + Ready, |
| 30 | + /// Waiting for a message on one of the actor's `waiting_tags`. |
| 31 | + Receive { |
| 32 | + deadline: Option<u64>, |
| 33 | + }, |
| 34 | + Sleep { |
| 35 | + deadline: u64, |
| 36 | + }, |
| 37 | + /// In a `blocking` extern call (never woken early, not even by a kill). |
| 38 | + Blocking, |
| 39 | + /// Waiting for a socket (`net`). |
| 40 | + Io, |
| 41 | +} |
| 42 | + |
| 43 | +/// How long a receive waits. |
| 44 | +#[derive(Clone, Copy)] |
| 45 | +pub(crate) enum Timeout { |
| 46 | + /// Not at all: `receive(_, 0)`. |
| 47 | + Zero, |
| 48 | + /// Until this time on the scheduler's clock. |
| 49 | + At(u64), |
| 50 | + Never, |
| 51 | +} |
| 52 | + |
| 53 | +/// What a receive did. |
| 54 | +pub(crate) enum Received<V> { |
| 55 | + /// It took a message (or timed out at once): what it returns. |
| 56 | + Now(V), |
| 57 | + /// The actor waits; the wait's number, for its timer. |
| 58 | + Parked(u64), |
| 59 | +} |
| 60 | + |
| 61 | +/// What an exit leaves to its caller (after releasing the lock). |
| 62 | +pub(crate) struct Exited { |
| 63 | + /// The linked actors, to stop or signal, in the order they were linked. |
| 64 | + pub(crate) links: Vec<i64>, |
| 65 | + /// (watcher, tag): who receives `Down`. |
| 66 | + pub(crate) monitors: Vec<(i64, i64)>, |
| 67 | + /// Whether the actor must be scheduled, to unwind. |
| 68 | + pub(crate) wake: bool, |
| 69 | +} |
| 70 | + |
| 71 | +/// The actors an actor is linked to, in the order they were linked (the |
| 72 | +/// order exits propagate in). Membership and removal take constant time: |
| 73 | +/// an actor linked to each of 100,000 short-lived children removed each |
| 74 | +/// child from a vector as it exited, quadratic time that dominated |
| 75 | +/// `tests/stress/actors.lse` once children no longer ran as soon as they |
| 76 | +/// were spawned (issue #61). |
| 77 | +#[derive(Default)] |
| 78 | +pub(crate) struct Links { |
| 79 | + /// Insertion order; removed links stay until compacted. |
| 80 | + order: Vec<i64>, |
| 81 | + live: std::collections::HashSet<i64, std::hash::BuildHasherDefault<IdHasher>>, |
| 82 | +} |
| 83 | + |
| 84 | +impl Links { |
| 85 | + /// Link `pid`, unless it already is. |
| 86 | + pub(crate) fn insert(&mut self, pid: i64) { |
| 87 | + if self.live.insert(pid) { |
| 88 | + self.order.push(pid); |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + pub(crate) fn remove(&mut self, pid: i64) { |
| 93 | + if self.live.remove(&pid) && self.order.len() > 2 * self.live.len() + 16 { |
| 94 | + self.order.retain(|p| self.live.contains(p)); |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + /// The linked actors, in order. |
| 99 | + pub(crate) fn into_vec(self) -> Vec<i64> { |
| 100 | + let mut live = self.live; |
| 101 | + // `remove` on a pid seen twice (unlinked, then linked again) keeps |
| 102 | + // its first place. |
| 103 | + self.order.into_iter().filter(|p| live.remove(p)).collect() |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +/// Messages by subject tag, each with its arrival number: receiving from |
| 108 | +/// one subject is O(1) however many other messages wait, and |
| 109 | +/// `receive_any` still takes the oldest of several subjects. |
| 110 | +pub(crate) struct Mailbox<V> { |
| 111 | + by_tag: IdMap<VecDeque<(u64, V)>>, |
| 112 | + arrived: u64, |
| 113 | +} |
| 114 | + |
| 115 | +impl<V> Default for Mailbox<V> { |
| 116 | + fn default() -> Self { |
| 117 | + Mailbox { |
| 118 | + by_tag: IdMap::default(), |
| 119 | + arrived: 0, |
| 120 | + } |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +impl<V> Mailbox<V> { |
| 125 | + fn push(&mut self, tag: i64, message: V) { |
| 126 | + self.arrived += 1; |
| 127 | + self.by_tag |
| 128 | + .entry(tag) |
| 129 | + .or_default() |
| 130 | + .push_back((self.arrived, message)); |
| 131 | + } |
| 132 | + |
| 133 | + /// The oldest message on one of `tags`, with its tag. |
| 134 | + fn take(&mut self, tags: &[i64]) -> Option<(i64, V)> { |
| 135 | + let tag = tags |
| 136 | + .iter() |
| 137 | + .filter_map(|t| Some((self.by_tag.get(t)?.front()?.0, *t))) |
| 138 | + .min()? |
| 139 | + .1; |
| 140 | + let queue = self.by_tag.get_mut(&tag)?; |
| 141 | + let (_, message) = queue.pop_front()?; |
| 142 | + if queue.is_empty() { |
| 143 | + self.by_tag.remove(&tag); |
| 144 | + } |
| 145 | + Some((tag, message)) |
| 146 | + } |
| 147 | + |
| 148 | + /// Every message left, to drop. |
| 149 | + pub(crate) fn drain(&mut self) -> impl Iterator<Item = V> { |
| 150 | + std::mem::take(&mut self.by_tag) |
| 151 | + .into_values() |
| 152 | + .flatten() |
| 153 | + .map(|(_, message)| message) |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +pub(crate) struct Proc<V, F> { |
| 158 | + mailbox: Mailbox<V>, |
| 159 | + pub(crate) wait: Wait, |
| 160 | + /// What a parked operation returns when woken. |
| 161 | + wake: V, |
| 162 | + pub(crate) links: Links, |
| 163 | + /// (watcher, tag): who receives `Down` when this actor exits. |
| 164 | + pub(crate) monitors: Vec<(i64, i64)>, |
| 165 | + pub(crate) trap: bool, |
| 166 | + pub(crate) exits_tag: Option<i64>, |
| 167 | + /// While `wait` is `Receive`: the tags waited on, and whether the |
| 168 | + /// answer carries the tag (`receive_any`). |
| 169 | + waiting_tags: Vec<i64>, |
| 170 | + waiting_any: bool, |
| 171 | + /// Counts waits, so a timer set for an earlier one is ignored. |
| 172 | + wait_gen: u64, |
| 173 | + /// Exited (logically); its fiber may still have to unwind. |
| 174 | + pub(crate) dead: bool, |
| 175 | + pub(crate) run: RunState<F>, |
| 176 | +} |
| 177 | + |
| 178 | +impl<V: Answer, F> Proc<V, F> { |
| 179 | + /// A new actor, queued (its caller pushes it right after). |
| 180 | + pub(crate) fn new(fiber: F, links: Links, monitors: Vec<(i64, i64)>) -> Self { |
| 181 | + let mut run = RunState::new(fiber); |
| 182 | + run.queue_new(); |
| 183 | + Proc { |
| 184 | + mailbox: Mailbox::default(), |
| 185 | + wait: Wait::Ready, |
| 186 | + wake: V::unit(), |
| 187 | + links, |
| 188 | + monitors, |
| 189 | + trap: false, |
| 190 | + exits_tag: None, |
| 191 | + waiting_tags: Vec::new(), |
| 192 | + waiting_any: false, |
| 193 | + wait_gen: 0, |
| 194 | + dead: false, |
| 195 | + run, |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + /// A message arrives on `tag`: handed to the actor if it waits for that |
| 200 | + /// tag, else kept in the mailbox. `Ok`: whether the caller must |
| 201 | + /// schedule the actor; `Err`: the message back, the actor has exited. |
| 202 | + pub(crate) fn deliver(&mut self, tag: i64, message: V) -> Result<bool, V> { |
| 203 | + if self.dead { |
| 204 | + return Err(message); |
| 205 | + } |
| 206 | + if matches!(self.wait, Wait::Receive { .. }) && self.waiting_tags.contains(&tag) { |
| 207 | + let answer = V::received(message, self.waiting_any.then_some(tag)); |
| 208 | + return Ok(self.wake(answer)); |
| 209 | + } |
| 210 | + self.mailbox.push(tag, message); |
| 211 | + Ok(false) |
| 212 | + } |
| 213 | + |
| 214 | + /// Take the oldest message on one of `tags`, or else wait for one |
| 215 | + /// (then the caller parks, after setting the timer). `any`: the answer |
| 216 | + /// carries the tag. |
| 217 | + pub(crate) fn receive(&mut self, tags: Vec<i64>, any: bool, timeout: Timeout) -> Received<V> { |
| 218 | + if let Some((tag, message)) = self.mailbox.take(&tags) { |
| 219 | + return Received::Now(V::received(message, any.then_some(tag))); |
| 220 | + } |
| 221 | + let deadline = match timeout { |
| 222 | + Timeout::Zero => return Received::Now(V::timed_out()), |
| 223 | + Timeout::At(d) => Some(d), |
| 224 | + Timeout::Never => None, |
| 225 | + }; |
| 226 | + self.waiting_tags = tags; |
| 227 | + self.waiting_any = any; |
| 228 | + Received::Parked(self.park_as(Wait::Receive { deadline })) |
| 229 | + } |
| 230 | + |
| 231 | + /// Make the actor ready; its parked operation returns `value`. |
| 232 | + /// Returns whether the caller must schedule it (after releasing the |
| 233 | + /// lock). |
| 234 | + pub(crate) fn wake(&mut self, value: V) -> bool { |
| 235 | + self.wait = Wait::Ready; |
| 236 | + self.wake = value; |
| 237 | + self.run.wake() |
| 238 | + } |
| 239 | + |
| 240 | + /// Wake it unless it is ready or in a blocking call. |
| 241 | + pub(crate) fn interrupt(&mut self) -> bool { |
| 242 | + if self.wait != Wait::Ready && self.wait != Wait::Blocking { |
| 243 | + return self.wake(V::unit()); |
| 244 | + } |
| 245 | + false |
| 246 | + } |
| 247 | + |
| 248 | + /// Start waiting as `wait`; returns the wait's number, for its timer. |
| 249 | + /// |
| 250 | + /// An actor that exited while it ran (killed, or a linked actor |
| 251 | + /// crashed) does not wait: its exit found it ready, so nothing would |
| 252 | + /// wake it. It stays ready, its thread queues it again when it yields, |
| 253 | + /// and it unwinds. Except in a blocking call, which runs to its end |
| 254 | + /// (it still reads the actor's values). |
| 255 | + pub(crate) fn park_as(&mut self, wait: Wait) -> u64 { |
| 256 | + self.wait_gen += 1; |
| 257 | + if !self.dead || wait == Wait::Blocking { |
| 258 | + self.wait = wait; |
| 259 | + } |
| 260 | + self.wait_gen |
| 261 | + } |
| 262 | + |
| 263 | + /// Whether the actor is still in wait number `wait`, until `deadline` |
| 264 | + /// (else that wait's timer no longer applies). |
| 265 | + pub(crate) fn waits_until(&self, wait: u64, deadline: u64) -> bool { |
| 266 | + let current = match self.wait { |
| 267 | + Wait::Receive { |
| 268 | + deadline: Some(d), .. |
| 269 | + } |
| 270 | + | Wait::Sleep { deadline: d } => Some(d), |
| 271 | + _ => None, |
| 272 | + }; |
| 273 | + self.wait_gen == wait && current == Some(deadline) |
| 274 | + } |
| 275 | + |
| 276 | + /// The timer of wait number `wait` is due: end that wait, if it is |
| 277 | + /// still on. A receive returns `None`, a sleep `()`. Returns whether |
| 278 | + /// the caller must schedule the actor. |
| 279 | + pub(crate) fn time_out(&mut self, wait: u64, deadline: u64) -> bool { |
| 280 | + if !self.waits_until(wait, deadline) { |
| 281 | + return false; |
| 282 | + } |
| 283 | + let value = match self.wait { |
| 284 | + Wait::Sleep { .. } => V::unit(), |
| 285 | + _ => V::timed_out(), |
| 286 | + }; |
| 287 | + self.wake(value) |
| 288 | + } |
| 289 | + |
| 290 | + /// The actor exits: from now on, messages are refused and its wait is |
| 291 | + /// interrupted. `None` if it had already exited. |
| 292 | + pub(crate) fn exit(&mut self) -> Option<Exited> { |
| 293 | + if self.dead { |
| 294 | + return None; |
| 295 | + } |
| 296 | + self.dead = true; |
| 297 | + Some(Exited { |
| 298 | + links: std::mem::take(&mut self.links).into_vec(), |
| 299 | + monitors: std::mem::take(&mut self.monitors), |
| 300 | + wake: self.interrupt(), |
| 301 | + }) |
| 302 | + } |
| 303 | + |
| 304 | + /// What the woken operation returns (the actor resumed). |
| 305 | + pub(crate) fn take_wake(&mut self) -> V { |
| 306 | + std::mem::replace(&mut self.wake, V::unit()) |
| 307 | + } |
| 308 | + |
| 309 | + /// The actor's fiber yielded: whether the caller must queue it again |
| 310 | + /// (it was preempted, or woken before it stopped). |
| 311 | + pub(crate) fn stop(&mut self, fiber: F) -> bool { |
| 312 | + let ready = self.wait == Wait::Ready; |
| 313 | + self.run.stop(fiber, ready) |
| 314 | + } |
| 315 | + |
| 316 | + /// What the actor still holds once it exited, to drop: nothing is |
| 317 | + /// delivered to it any more. |
| 318 | + pub(crate) fn release(&mut self) -> (Mailbox<V>, V) { |
| 319 | + debug_assert!(self.dead); |
| 320 | + (std::mem::take(&mut self.mailbox), self.take_wake()) |
| 321 | + } |
| 322 | +} |
| 323 | + |
| 324 | +/// The models' values: messages are numbered, so that each can be found |
| 325 | +/// again wherever it ended up. |
| 326 | +#[cfg(test)] |
| 327 | +#[derive(Clone, Copy, Debug, PartialEq)] |
| 328 | +enum Val { |
| 329 | + Unit, |
| 330 | + TimedOut, |
| 331 | + Message(u32), |
| 332 | + Received(u32, Option<i64>), |
| 333 | +} |
| 334 | + |
| 335 | +#[cfg(test)] |
| 336 | +impl Answer for Val { |
| 337 | + fn received(message: Val, tag: Option<i64>) -> Val { |
| 338 | + match message { |
| 339 | + Val::Message(n) => Val::Received(n, tag), |
| 340 | + other => panic!("not a message: {other:?}"), |
| 341 | + } |
| 342 | + } |
| 343 | + |
| 344 | + fn timed_out() -> Val { |
| 345 | + Val::TimedOut |
| 346 | + } |
| 347 | + |
| 348 | + fn unit() -> Val { |
| 349 | + Val::Unit |
| 350 | + } |
| 351 | +} |
| 352 | + |
| 353 | +#[cfg(all(test, loom))] |
| 354 | +mod loom_models { |
| 355 | + //! Each model starts with the actor running (taken from a run queue), |
| 356 | + //! as the thread that took it leaves it, and plays the actor's side on |
| 357 | + //! the model's main thread: a receive, then, if it waits, its fiber |
| 358 | + //! yields and that thread stops it, under the lock again. `queued` |
| 359 | + //! counts the times a thread puts the actor in a run queue. |
| 360 | + //! |
| 361 | + //! A kill is modelled by `Proc::exit` alone: the kill flag the actor |
| 362 | + //! reads at its safe points is set under the same lock, just before. |
| 363 | + use super::*; |
| 364 | + use loom::sync::atomic::{AtomicUsize, Ordering}; |
| 365 | + use loom::sync::{Arc, Mutex}; |
| 366 | + use loom::thread; |
| 367 | + |
| 368 | + const A: i64 = 1; |
| 369 | + const B: i64 = 2; |
| 370 | + |
| 371 | + type Shared = Arc<Mutex<Proc<Val, ()>>>; |
| 372 | + |
| 373 | + fn running() -> (Shared, Arc<AtomicUsize>) { |
| 374 | + let mut p = Proc::new((), Links::default(), Vec::new()); |
| 375 | + assert!(p.run.start().is_some()); |
| 376 | + (Arc::new(Mutex::new(p)), Arc::new(AtomicUsize::new(0))) |
| 377 | + } |
| 378 | + |
| 379 | + /// A thread that sends `message` on `tag`; it returns the message if |
| 380 | + /// the actor refused it (the sender then frees it). |
| 381 | + fn sender( |
| 382 | + actor: &Shared, |
| 383 | + queued: &Arc<AtomicUsize>, |
| 384 | + tag: i64, |
| 385 | + message: u32, |
| 386 | + ) -> thread::JoinHandle<Option<Val>> { |
| 387 | + let (actor, queued) = (actor.clone(), queued.clone()); |
| 388 | + thread::spawn(move || { |
| 389 | + let delivered = actor.lock().unwrap().deliver(tag, Val::Message(message)); |
| 390 | + match delivered { |
| 391 | + Ok(true) => { |
| 392 | + queued.fetch_add(1, Ordering::SeqCst); |
| 393 | + None |
| 394 | + } |
| 395 | + Ok(false) => None, |
| 396 | + Err(refused) => Some(refused), |
| 397 | + } |
| 398 | + }) |
| 399 | + } |
| 400 | + |
| 401 | + /// The actor's side: receive on `tags`; if it waits, return the |
| 402 | + /// wait's number after its thread stopped it. |
| 403 | + fn receive( |
| 404 | + actor: &Shared, |
| 405 | + queued: &AtomicUsize, |
| 406 | + tags: &[i64], |
| 407 | + timeout: Timeout, |
| 408 | + ) -> Received<Val> { |
| 409 | + let received = actor.lock().unwrap().receive(tags.to_vec(), false, timeout); |
| 410 | + if let Received::Parked(_) = received |
| 411 | + && actor.lock().unwrap().stop(()) |
| 412 | + { |
| 413 | + queued.fetch_add(1, Ordering::SeqCst); |
| 414 | + } |
| 415 | + received |
| 416 | + } |
| 417 | + |
| 418 | + /// The actor, queued, runs again: what its receive returns. |
| 419 | + fn resume(actor: &Shared) -> Val { |
| 420 | + let mut p = actor.lock().unwrap(); |
| 421 | + assert!(p.run.start().is_some(), "queued while not suspended"); |
| 422 | + p.take_wake() |
| 423 | + } |
| 424 | + |
| 425 | + /// What is left in the mailbox on `tag` (checked without waiting). |
| 426 | + fn left(actor: &Shared, tag: i64) -> Val { |
| 427 | + match actor |
| 428 | + .lock() |
| 429 | + .unwrap() |
| 430 | + .receive(vec![tag], false, Timeout::Zero) |
| 431 | + { |
| 432 | + Received::Now(v) => v, |
| 433 | + Received::Parked(_) => unreachable!("a zero timeout never waits"), |
| 434 | + } |
| 435 | + } |
| 436 | + |
| 437 | + /// Two messages race with a receive on one of their tags: the receive |
| 438 | + /// gets the first, at once or woken exactly once; the other stays in |
| 439 | + /// the mailbox and wakes nobody. |
| 440 | + #[test] |
| 441 | + fn sends_race_a_receive() { |
| 442 | + loom::model(|| { |
| 443 | + let (actor, queued) = running(); |
| 444 | + let to_a = sender(&actor, &queued, A, 1); |
| 445 | + let to_b = sender(&actor, &queued, B, 2); |
| 446 | + let received = receive(&actor, &queued, &[A], Timeout::Never); |
| 447 | + assert_eq!(to_a.join().unwrap(), None); |
| 448 | + assert_eq!(to_b.join().unwrap(), None); |
| 449 | + match received { |
| 450 | + Received::Now(v) => { |
| 451 | + assert_eq!(v, Val::Received(1, None)); |
| 452 | + assert_eq!(queued.load(Ordering::SeqCst), 0); |
| 453 | + } |
| 454 | + Received::Parked(_) => { |
| 455 | + assert_eq!(queued.load(Ordering::SeqCst), 1); |
| 456 | + assert_eq!(resume(&actor), Val::Received(1, None)); |
| 457 | + } |
| 458 | + } |
| 459 | + assert_eq!(left(&actor, A), Val::TimedOut); |
| 460 | + assert_eq!(left(&actor, B), Val::Received(2, None)); |
| 461 | + }); |
| 462 | + } |
| 463 | + |
| 464 | + /// A receive's timer fires while its message arrives: the receive |
| 465 | + /// returns the message or `None`, not both, and a message it did not |
| 466 | + /// return is still in the mailbox. The actor is queued once. |
| 467 | + #[test] |
| 468 | + fn a_timeout_races_a_send() { |
| 469 | + loom::model(|| { |
| 470 | + let (actor, queued) = running(); |
| 471 | + let send = sender(&actor, &queued, A, 1); |
| 472 | + let received = receive(&actor, &queued, &[A], Timeout::At(10)); |
| 473 | + // The timer is set once the actor waits (`take_or_wait`). |
| 474 | + let timer = match received { |
| 475 | + Received::Parked(wait) => { |
| 476 | + let (actor, queued) = (actor.clone(), queued.clone()); |
| 477 | + Some(thread::spawn(move || { |
| 478 | + if actor.lock().unwrap().time_out(wait, 10) { |
| 479 | + queued.fetch_add(1, Ordering::SeqCst); |
| 480 | + } |
| 481 | + })) |
| 482 | + } |
| 483 | + Received::Now(v) => { |
| 484 | + assert_eq!(v, Val::Received(1, None)); |
| 485 | + None |
| 486 | + } |
| 487 | + }; |
| 488 | + assert_eq!(send.join().unwrap(), None); |
| 489 | + if let Some(timer) = timer { |
| 490 | + timer.join().unwrap(); |
| 491 | + assert_eq!(queued.load(Ordering::SeqCst), 1); |
| 492 | + match resume(&actor) { |
| 493 | + Val::Received(1, None) => assert_eq!(left(&actor, A), Val::TimedOut), |
| 494 | + Val::TimedOut => assert_eq!(left(&actor, A), Val::Received(1, None)), |
| 495 | + other => panic!("woken with {other:?}"), |
| 496 | + } |
| 497 | + } else { |
| 498 | + assert_eq!(queued.load(Ordering::SeqCst), 0); |
| 499 | + } |
| 500 | + }); |
| 501 | + } |
| 502 | + |
| 503 | + /// The actor is killed while a message arrives and it receives: the |
| 504 | + /// message is received, refused (back to its sender), left in the |
| 505 | + /// mailbox or left as the wake value, exactly one of them, for the |
| 506 | + /// actor to free as it unwinds. A waiting actor is queued once, to |
| 507 | + /// unwind. |
| 508 | + #[test] |
| 509 | + fn a_kill_races_a_send_and_a_receive() { |
| 510 | + loom::model(|| { |
| 511 | + let (actor, queued) = running(); |
| 512 | + let send = sender(&actor, &queued, A, 1); |
| 513 | + let kill = { |
| 514 | + let (actor, queued) = (actor.clone(), queued.clone()); |
| 515 | + thread::spawn(move || { |
| 516 | + let exited = actor.lock().unwrap().exit().expect("exits once"); |
| 517 | + if exited.wake { |
| 518 | + queued.fetch_add(1, Ordering::SeqCst); |
| 519 | + } |
| 520 | + }) |
| 521 | + }; |
| 522 | + let received = receive(&actor, &queued, &[A], Timeout::Never); |
| 523 | + let refused = send.join().unwrap(); |
| 524 | + kill.join().unwrap(); |
| 525 | + let mut found = Vec::new(); |
| 526 | + if let Received::Now(v) = received { |
| 527 | + assert_eq!(queued.load(Ordering::SeqCst), 0); |
| 528 | + found.push(v); |
| 529 | + } else { |
| 530 | + assert_eq!(queued.load(Ordering::SeqCst), 1); |
| 531 | + // It unwinds: what woke it is dropped, as `sched::park` does. |
| 532 | + match resume(&actor) { |
| 533 | + Val::Unit => {} |
| 534 | + v => found.push(v), |
| 535 | + } |
| 536 | + } |
| 537 | + found.extend(refused); |
| 538 | + let (mut mailbox, wake) = actor.lock().unwrap().release(); |
| 539 | + assert_eq!(wake, Val::Unit, "the wake value was taken when it resumed"); |
| 540 | + found.extend(mailbox.drain()); |
| 541 | + let ones = found |
| 542 | + .iter() |
| 543 | + .filter(|v| matches!(v, Val::Message(1) | Val::Received(1, _))) |
| 544 | + .count(); |
| 545 | + assert_eq!(ones, 1, "the message, once: {found:?}"); |
| 546 | + }); |
| 547 | + } |
| 548 | +} |
| 549 | + |
| 550 | +#[cfg(test)] |
| 551 | +mod tests { |
| 552 | + use super::*; |
| 553 | + |
| 554 | + fn actor() -> Proc<Val, ()> { |
| 555 | + let mut p = Proc::new((), Links::default(), Vec::new()); |
| 556 | + assert!(p.run.start().is_some()); |
| 557 | + p |
| 558 | + } |
| 559 | + |
| 560 | + fn parked(r: Received<Val>) -> u64 { |
| 561 | + match r { |
| 562 | + Received::Parked(wait) => wait, |
| 563 | + Received::Now(v) => panic!("received {v:?}"), |
| 564 | + } |
| 565 | + } |
| 566 | + |
| 567 | + #[test] |
| 568 | + fn receive_any_takes_the_oldest_and_names_its_tag() { |
| 569 | + let mut p = actor(); |
| 570 | + for (tag, n) in [(2, 1), (1, 2), (2, 3)] { |
| 571 | + assert_eq!(p.deliver(tag, Val::Message(n)), Ok(false)); |
| 572 | + } |
| 573 | + assert!(matches!( |
| 574 | + p.receive(vec![1, 2], true, Timeout::Zero), |
| 575 | + Received::Now(Val::Received(1, Some(2))) |
| 576 | + )); |
| 577 | + assert!(matches!( |
| 578 | + p.receive(vec![1], false, Timeout::Zero), |
| 579 | + Received::Now(Val::Received(2, None)) |
| 580 | + )); |
| 581 | + } |
| 582 | + |
| 583 | + #[test] |
| 584 | + fn a_timer_for_an_earlier_wait_is_ignored() { |
| 585 | + let mut p = actor(); |
| 586 | + let first = parked(p.receive(vec![1], false, Timeout::At(10))); |
| 587 | + assert!(!p.stop(())); |
| 588 | + assert_eq!(p.deliver(1, Val::Message(1)), Ok(true)); |
| 589 | + assert!(p.run.start().is_some()); |
| 590 | + assert_eq!(p.take_wake(), Val::Received(1, None)); |
| 591 | + // Waiting again, with the same deadline. |
| 592 | + let second = parked(p.receive(vec![1], false, Timeout::At(10))); |
| 593 | + assert!(!p.stop(())); |
| 594 | + assert!(!p.time_out(first, 10), "the first wait's timer"); |
| 595 | + assert!(p.time_out(second, 10)); |
| 596 | + assert!(p.run.start().is_some()); |
| 597 | + assert_eq!(p.take_wake(), Val::TimedOut); |
| 598 | + } |
| 599 | + |
| 600 | + /// Killed while it ran, then it receives: it does not wait, so that it |
| 601 | + /// is queued again to unwind (found by `a_kill_races_a_send_and_a_receive`). |
| 602 | + #[test] |
| 603 | + fn an_actor_killed_while_running_does_not_wait() { |
| 604 | + for wait in [Wait::Io, Wait::Sleep { deadline: 5 }] { |
| 605 | + let mut p = actor(); |
| 606 | + assert!(!p.exit().expect("alive").wake, "running: nothing to wake"); |
| 607 | + p.park_as(wait); |
| 608 | + assert!(p.stop(()), "{wait:?}: queued again, to unwind"); |
| 609 | + } |
| 610 | + let mut p = actor(); |
| 611 | + p.exit(); |
| 612 | + parked(p.receive(vec![1], false, Timeout::Never)); |
| 613 | + assert!(p.stop(())); |
| 614 | + } |
| 615 | + |
| 616 | + #[test] |
| 617 | + fn an_exited_actor_refuses_messages_and_a_blocking_call_is_not_interrupted() { |
| 618 | + let mut p = actor(); |
| 619 | + p.park_as(Wait::Blocking); |
| 620 | + assert!(!p.stop(())); |
| 621 | + assert!( |
| 622 | + !p.exit().expect("alive").wake, |
| 623 | + "a blocking call runs to its end" |
| 624 | + ); |
| 625 | + assert!(p.exit().is_none(), "exits once"); |
| 626 | + assert_eq!(p.deliver(1, Val::Message(1)), Err(Val::Message(1))); |
| 627 | + } |
| 628 | + |
| 629 | + #[test] |
| 630 | + fn links_keep_their_order_and_drop_removed_ones() { |
| 631 | + let mut links = Links::default(); |
| 632 | + for pid in [5, 3, 9, 3, 7] { |
| 633 | + links.insert(pid); |
| 634 | + } |
| 635 | + links.remove(9); |
| 636 | + links.remove(42); |
| 637 | + assert_eq!(links.into_vec(), [5, 3, 7]); |
| 638 | + // Many removals compact the order, without changing it. |
| 639 | + let mut links = Links::default(); |
| 640 | + for pid in 0..1000 { |
| 641 | + links.insert(pid); |
| 642 | + } |
| 643 | + for pid in (0..1000).filter(|p| p % 10 != 0) { |
| 644 | + links.remove(pid); |
| 645 | + } |
| 646 | + assert!(links.order.len() < 300); |
| 647 | + assert_eq!(links.into_vec(), (0..1000).step_by(10).collect::<Vec<_>>()); |
| 648 | + } |
| 649 | +} |