use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
type Task = Pin<Box<dyn Future<Output = ()> + Send>>;
pub struct Executor {
inner: Arc<Shared>,
}
struct Shared {
tasks: Mutex<HashMap<u64, Task>>,
ready: Mutex<Option<mpsc::Sender<u64>>>,
next: AtomicU64,
}
struct TaskWaker {
id: u64,
shared: Arc<Shared>,
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
if let Some(ready) = self.shared.ready.lock().unwrap().as_ref() {
let _ = ready.send(self.id);
}
}
}
impl Default for Executor {
fn default() -> Self {
Self::new()
}
}
impl Executor {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel::<u64>();
let inner = Arc::new(Shared {
tasks: Mutex::new(HashMap::new()),
ready: Mutex::new(Some(sender)),
next: AtomicU64::new(1),
});
let shared = inner.clone();
std::thread::Builder::new()
.name("webbluetooth-node".into())
.spawn(move || {
while let Ok(id) = receiver.recv() {
let Some(mut task) = shared.tasks.lock().unwrap().remove(&id) else {
continue; };
let waker: Waker = Arc::new(TaskWaker {
id,
shared: shared.clone(),
})
.into();
if task.as_mut().poll(&mut Context::from_waker(&waker)) == Poll::Pending {
shared.tasks.lock().unwrap().insert(id, task);
}
}
})
.expect("could not start the webbluetooth executor thread");
Self { inner }
}
pub fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) -> bool {
let id = self.inner.next.fetch_add(1, Ordering::Relaxed);
self.inner
.tasks
.lock()
.unwrap()
.insert(id, Box::pin(future));
let queued = self
.inner
.ready
.lock()
.unwrap()
.as_ref()
.map(|r| r.send(id).is_ok())
.unwrap_or(false);
if !queued {
self.inner.tasks.lock().unwrap().remove(&id);
}
queued
}
#[allow(dead_code)]
pub fn in_flight(&self) -> usize {
self.inner.tasks.lock().unwrap().len()
}
}
impl Drop for Executor {
fn drop(&mut self) {
self.inner.ready.lock().unwrap().take();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicUsize;
use std::time::{Duration, Instant};
struct Gate(Arc<GateState>);
struct GateState {
open: Mutex<bool>,
waker: Mutex<Option<Waker>>,
}
impl GateState {
fn new() -> Arc<Self> {
Arc::new(Self {
open: Mutex::new(false),
waker: Mutex::new(None),
})
}
fn open(self: &Arc<Self>) {
*self.open.lock().unwrap() = true;
if let Some(w) = self.waker.lock().unwrap().take() {
w.wake();
}
}
}
impl Future for Gate {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if *self.0.open.lock().unwrap() {
return Poll::Ready(());
}
*self.0.waker.lock().unwrap() = Some(cx.waker().clone());
Poll::Pending
}
}
fn eventually(mut done: impl FnMut() -> bool) -> bool {
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if done() {
return true;
}
std::thread::sleep(Duration::from_millis(1));
}
false
}
#[test]
fn a_future_that_never_waits_finishes() {
let executor = Executor::new();
let ran = Arc::new(AtomicUsize::new(0));
let flag = ran.clone();
executor.spawn(async move {
flag.fetch_add(1, Ordering::SeqCst);
});
assert!(eventually(|| ran.load(Ordering::SeqCst) == 1));
assert!(eventually(|| executor.in_flight() == 0));
}
#[test]
fn operations_do_not_queue_behind_each_other() {
let executor = Executor::new();
let first = GateState::new();
let second = GateState::new();
let done = Arc::new(AtomicUsize::new(0));
for gate in [first.clone(), second.clone()] {
let done = done.clone();
executor.spawn(async move {
Gate(gate).await;
done.fetch_add(1, Ordering::SeqCst);
});
}
assert!(eventually(|| executor.in_flight() == 2));
assert_eq!(done.load(Ordering::SeqCst), 0);
second.open();
assert!(eventually(|| done.load(Ordering::SeqCst) == 1));
first.open();
assert!(eventually(|| done.load(Ordering::SeqCst) == 2));
assert!(eventually(|| executor.in_flight() == 0));
}
#[test]
fn many_operations_run_concurrently() {
const N: usize = 64;
let executor = Executor::new();
let gates: Vec<_> = (0..N).map(|_| GateState::new()).collect();
let done = Arc::new(AtomicUsize::new(0));
for gate in &gates {
let (gate, done) = (gate.clone(), done.clone());
executor.spawn(async move {
Gate(gate).await;
done.fetch_add(1, Ordering::SeqCst);
});
}
assert!(eventually(|| executor.in_flight() == N));
let threads: Vec<_> = gates
.chunks(8)
.map(|chunk| {
let chunk: Vec<_> = chunk.to_vec();
std::thread::spawn(move || {
for gate in chunk {
gate.open();
}
})
})
.collect();
for t in threads {
t.join().expect("no thread should have panicked");
}
assert!(eventually(|| done.load(Ordering::SeqCst) == N));
assert!(eventually(|| executor.in_flight() == 0));
}
#[test]
fn a_wake_during_a_poll_is_not_lost() {
struct WakeFromInside(usize);
impl Future for WakeFromInside {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
self.0 += 1;
if self.0 >= 4 {
return Poll::Ready(());
}
cx.waker().wake_by_ref();
Poll::Pending
}
}
let executor = Executor::new();
let done = Arc::new(AtomicUsize::new(0));
let flag = done.clone();
executor.spawn(async move {
WakeFromInside(0).await;
flag.fetch_add(1, Ordering::SeqCst);
});
assert!(eventually(|| done.load(Ordering::SeqCst) == 1));
assert!(eventually(|| executor.in_flight() == 0));
}
#[test]
fn work_submitted_after_shutdown_is_refused_and_dropped() {
let executor = Executor::new();
let inner = executor.inner.clone();
drop(executor);
let outer = Executor { inner };
assert!(
!outer.spawn(async {}),
"a closed executor should refuse work"
);
assert_eq!(outer.in_flight(), 0, "and not hold onto it");
std::mem::forget(outer);
}
}