refactor: centralize runtime logic (v0.4)

Extract scheduler responsibilities into a dedicated Runtime component:
- src/runtime.rs: New centralized control flow (669 lines)
- src/scheduler.rs: Simplified to task queue & preemption management
- tests/runtime.rs: Comprehensive runtime test suite
- benches/multi_scheduler.rs: Multi-runtime scheduling benchmarks
- Improves modularity and enables per-runtime configuration
This commit is contained in:
Claude
2026-05-23 16:09:32 +00:00
parent 8cbef1dfc1
commit e9fdbb1160
10 changed files with 1694 additions and 919 deletions
+14 -34
View File
@@ -1,12 +1,8 @@
//! Unbounded MPSC channels.
//!
//! Single-threaded scheduler: the inner state is `Rc<RefCell<Inner<T>>>`,
//! not `Arc<Mutex>`. We hand-implement `Send` for `Sender<T>` and
//! `Receiver<T>` when `T: Send`, on the basis that the only way two actor
//! contexts touch the same channel is by being scheduled on the *same* OS
//! thread (v0.1 has exactly one). When we add a second scheduler thread,
//! this lie must be retired: replace `Rc<RefCell>` with `Arc<Mutex>` (or a
//! lock-free queue) and remove the unsafe Send impls.
//! Inner state is `Arc<Mutex<Inner<T>>>` so channels can be sent across OS
//! threads (required for the multi-scheduler runtime where a sender and
//! receiver may run on different scheduler threads simultaneously).
//!
//! Semantics:
//! - Senders are clonable; the last sender drop closes the channel.
@@ -19,12 +15,11 @@
//! parked, the receiver is unparked.
use crate::pid::Pid;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let inner = Rc::new(RefCell::new(Inner {
let inner = Arc::new(Mutex::new(Inner {
queue: VecDeque::new(),
parked_receiver: None,
senders: 1,
@@ -41,20 +36,13 @@ struct Inner<T> {
}
pub struct Sender<T> {
inner: Rc<RefCell<Inner<T>>>,
inner: Arc<Mutex<Inner<T>>>,
}
pub struct Receiver<T> {
inner: Rc<RefCell<Inner<T>>>,
inner: Arc<Mutex<Inner<T>>>,
}
// SAFETY (v0.1 only): the scheduler is single-threaded. Sender/Receiver can
// be captured into actor closures (which require Send), but they will only
// ever be touched from one OS thread. When multi-threading lands, swap the
// `Rc<RefCell>` for `Arc<Mutex>` and remove these.
unsafe impl<T: Send> Send for Sender<T> {}
unsafe impl<T: Send> Send for Receiver<T> {}
#[derive(Debug, PartialEq, Eq)]
pub struct SendError<T>(pub T);
@@ -71,7 +59,7 @@ impl std::error::Error for RecvError {}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Self {
self.inner.borrow_mut().senders += 1;
self.inner.lock().unwrap().senders += 1;
Sender { inner: self.inner.clone() }
}
}
@@ -79,11 +67,9 @@ impl<T> Clone for Sender<T> {
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
let unpark = {
let mut g = self.inner.borrow_mut();
let mut g = self.inner.lock().unwrap();
g.senders -= 1;
if g.senders == 0 && g.queue.is_empty() {
// Channel closed and drained. Wake the receiver so it can
// see RecvError.
g.parked_receiver.take()
} else {
None
@@ -97,19 +83,18 @@ impl<T> Drop for Sender<T> {
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
self.inner.borrow_mut().receiver_alive = false;
self.inner.lock().unwrap().receiver_alive = false;
}
}
impl<T> Sender<T> {
pub fn send(&self, value: T) -> Result<(), SendError<T>> {
let unpark = {
let mut g = self.inner.borrow_mut();
let mut g = self.inner.lock().unwrap();
if !g.receiver_alive {
return Err(SendError(value));
}
g.queue.push_back(value);
// If the receiver is parked, unpark it.
g.parked_receiver.take()
};
if let Some(pid) = unpark {
@@ -122,16 +107,14 @@ impl<T> Sender<T> {
impl<T> Receiver<T> {
pub fn recv(&self) -> Result<T, RecvError> {
loop {
// Try to take a message.
{
let mut g = self.inner.borrow_mut();
let mut g = self.inner.lock().unwrap();
if let Some(v) = g.queue.pop_front() {
return Ok(v);
}
if g.senders == 0 {
return Err(RecvError);
}
// Empty + open: register and park.
let me = crate::actor::current_pid()
.expect("recv() called outside an actor");
debug_assert!(
@@ -140,18 +123,15 @@ impl<T> Receiver<T> {
);
g.parked_receiver = Some(me);
}
// Release the borrow before parking — the unparker will need it.
// Release the lock before parking — the unparker will need it.
crate::scheduler::park_current();
// Loop: the message that woke us might already have been taken
// (it can't, with one receiver, but the senders=0 path can fire
// here too).
}
}
/// Non-blocking. `Ok(Some(v))` if a message was available, `Ok(None)` if
/// the channel is empty but open, `Err(RecvError)` if closed and drained.
pub fn try_recv(&self) -> Result<Option<T>, RecvError> {
let mut g = self.inner.borrow_mut();
let mut g = self.inner.lock().unwrap();
if let Some(v) = g.queue.pop_front() {
return Ok(Some(v));
}