1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
use crate::{debug_state, Executor, LocalExecutor, State};
use async_task::{Builder, Runnable, Task};
use slab::Slab;
use std::{
cell::UnsafeCell,
fmt,
future::Future,
marker::PhantomData,
panic::{RefUnwindSafe, UnwindSafe},
};
impl Executor<'static> {
/// Consumes the [`Executor`] and intentionally leaks it.
///
/// Largely equivalent to calling `Box::leak(Box::new(executor))`, but the produced
/// [`StaticExecutor`]'s functions are optimized to require fewer synchronizing operations
/// when spawning, running, and finishing tasks.
///
/// `StaticExecutor` cannot be converted back into a `Executor`, so this operation is
/// irreversible without the use of unsafe.
///
/// # Example
///
/// ```
/// use async_executor::Executor;
/// use futures_lite::future;
///
/// let ex = Executor::new().leak();
///
/// let task = ex.spawn(async {
/// println!("Hello world");
/// });
///
/// future::block_on(ex.run(task));
/// ```
pub fn leak(self) -> &'static StaticExecutor {
let ptr = self.state_ptr();
// SAFETY: So long as an Executor lives, it's state pointer will always be valid
// when accessed through state_ptr. This executor will live for the full 'static
// lifetime so this isn't an arbitrary lifetime extension.
let state: &'static State = unsafe { &*ptr };
std::mem::forget(self);
let mut active = state.active.lock().unwrap();
if !active.is_empty() {
// Reschedule all of the active tasks.
for waker in active.drain() {
waker.wake();
}
// Overwrite to ensure that the slab is deallocated.
*active = Slab::new();
}
// SAFETY: StaticExecutor has the same memory layout as State as it's repr(transparent).
// The lifetime is not altered: 'static -> 'static.
let static_executor: &'static StaticExecutor = unsafe { std::mem::transmute(state) };
static_executor
}
}
impl LocalExecutor<'static> {
/// Consumes the [`LocalExecutor`] and intentionally leaks it.
///
/// Largely equivalent to calling `Box::leak(Box::new(executor))`, but the produced
/// [`StaticLocalExecutor`]'s functions are optimized to require fewer synchronizing operations
/// when spawning, running, and finishing tasks.
///
/// `StaticLocalExecutor` cannot be converted back into a `Executor`, so this operation is
/// irreversible without the use of unsafe.
///
/// # Example
///
/// ```
/// use async_executor::LocalExecutor;
/// use futures_lite::future;
///
/// let ex = LocalExecutor::new().leak();
///
/// let task = ex.spawn(async {
/// println!("Hello world");
/// });
///
/// future::block_on(ex.run(task));
/// ```
pub fn leak(self) -> &'static StaticLocalExecutor {
let ptr = self.inner.state_ptr();
// SAFETY: So long as a LocalExecutor lives, it's state pointer will always be valid
// when accessed through state_ptr. This executor will live for the full 'static
// lifetime so this isn't an arbitrary lifetime extension.
let state: &'static State = unsafe { &*ptr };
std::mem::forget(self);
let mut active = state.active.lock().unwrap();
if !active.is_empty() {
// Reschedule all of the active tasks.
for waker in active.drain() {
waker.wake();
}
// Overwrite to ensure that the slab is deallocated.
*active = Slab::new();
}
// SAFETY: StaticLocalExecutor has the same memory layout as State as it's repr(transparent).
// The lifetime is not altered: 'static -> 'static.
let static_executor: &'static StaticLocalExecutor = unsafe { std::mem::transmute(state) };
static_executor
}
}
/// A static-lifetimed async [`Executor`].
///
/// This is primarily intended to be used in [`static`] variables, or types intended to be used, or can be created in non-static
/// contexts via [`Executor::leak`].
///
/// Spawning, running, and finishing tasks are optimized with the assumption that the executor will never be `Drop`'ed.
/// A static executor may require signficantly less overhead in both single-threaded and mulitthreaded use cases.
///
/// As this type does not implement `Drop`, losing the handle to the executor or failing
/// to consistently drive the executor with [`StaticExecutor::tick`] or
/// [`StaticExecutor::run`] will cause the all spawned tasks to permanently leak. Any
/// tasks at the time will not be cancelled.
///
/// [`static`]: https://doc.rust-lang.org/std/keyword.static.html
#[repr(transparent)]
pub struct StaticExecutor {
state: State,
}
// SAFETY: Executor stores no thread local state that can be accessed via other thread.
unsafe impl Send for StaticExecutor {}
// SAFETY: Executor internally synchronizes all of it's operations internally.
unsafe impl Sync for StaticExecutor {}
impl UnwindSafe for StaticExecutor {}
impl RefUnwindSafe for StaticExecutor {}
impl fmt::Debug for StaticExecutor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
debug_state(&self.state, "StaticExecutor", f)
}
}
impl StaticExecutor {
/// Creates a new StaticExecutor.
///
/// # Examples
///
/// ```
/// use async_executor::StaticExecutor;
///
/// static EXECUTOR: StaticExecutor = StaticExecutor::new();
/// ```
pub const fn new() -> Self {
Self {
state: State::new(),
}
}
/// Spawns a task onto the executor.
///
/// Note: unlike [`Executor::spawn`], this function requires being called with a `'static`
/// borrow on the executor.
///
/// # Examples
///
/// ```
/// use async_executor::StaticExecutor;
///
/// static EXECUTOR: StaticExecutor = StaticExecutor::new();
///
/// let task = EXECUTOR.spawn(async {
/// println!("Hello world");
/// });
/// ```
pub fn spawn<T: Send + 'static>(
&'static self,
future: impl Future<Output = T> + Send + 'static,
) -> Task<T> {
let (runnable, task) = Builder::new()
.propagate_panic(true)
.spawn(|()| future, self.schedule());
runnable.schedule();
task
}
/// Spawns a non-`'static` task onto the executor.
///
/// ## Safety
///
/// The caller must ensure that the returned task terminates
/// or is cancelled before the end of 'a.
pub unsafe fn spawn_scoped<'a, T: Send + 'a>(
&'static self,
future: impl Future<Output = T> + Send + 'a,
) -> Task<T> {
// SAFETY:
//
// - `future` is `Send`
// - `future` is not `'static`, but the caller guarantees that the
// task, and thus its `Runnable` must not live longer than `'a`.
// - `self.schedule()` is `Send`, `Sync` and `'static`, as checked below.
// Therefore we do not need to worry about what is done with the
// `Waker`.
let (runnable, task) = unsafe {
Builder::new()
.propagate_panic(true)
.spawn_unchecked(|()| future, self.schedule())
};
runnable.schedule();
task
}
/// Attempts to run a task if at least one is scheduled.
///
/// Running a scheduled task means simply polling its future once.
///
/// # Examples
///
/// ```
/// use async_executor::StaticExecutor;
///
/// static EXECUTOR: StaticExecutor = StaticExecutor::new();
///
/// assert!(!EXECUTOR.try_tick()); // no tasks to run
///
/// let task = EXECUTOR.spawn(async {
/// println!("Hello world");
/// });
///
/// assert!(EXECUTOR.try_tick()); // a task was found
/// ```
pub fn try_tick(&self) -> bool {
self.state.try_tick()
}
/// Runs a single task.
///
/// Running a task means simply polling its future once.
///
/// If no tasks are scheduled when this method is called, it will wait until one is scheduled.
///
/// # Examples
///
/// ```
/// use async_executor::StaticExecutor;
/// use futures_lite::future;
///
/// static EXECUTOR: StaticExecutor = StaticExecutor::new();
///
/// let task = EXECUTOR.spawn(async {
/// println!("Hello world");
/// });
///
/// future::block_on(EXECUTOR.tick()); // runs the task
/// ```
pub async fn tick(&self) {
self.state.tick().await;
}
/// Runs the executor until the given future completes.
///
/// # Examples
///
/// ```
/// use async_executor::StaticExecutor;
/// use futures_lite::future;
///
/// static EXECUTOR: StaticExecutor = StaticExecutor::new();
///
/// let task = EXECUTOR.spawn(async { 1 + 2 });
/// let res = future::block_on(EXECUTOR.run(async { task.await * 2 }));
///
/// assert_eq!(res, 6);
/// ```
pub async fn run<T>(&self, future: impl Future<Output = T>) -> T {
self.state.run(future).await
}
/// Returns a function that schedules a runnable task when it gets woken up.
fn schedule(&'static self) -> impl Fn(Runnable) + Send + Sync + 'static {
let state: &'static State = &self.state;
// TODO: If possible, push into the current local queue and notify the ticker.
move |runnable| {
state.queue.push(runnable).unwrap();
state.notify();
}
}
}
impl Default for StaticExecutor {
fn default() -> Self {
Self::new()
}
}
/// A static async [`LocalExecutor`] created from [`LocalExecutor::leak`].
///
/// This is primarily intended to be used in [`thread_local`] variables, or can be created in non-static
/// contexts via [`LocalExecutor::leak`].
///
/// Spawning, running, and finishing tasks are optimized with the assumption that the executor will never be `Drop`'ed.
/// A static executor may require signficantly less overhead in both single-threaded and mulitthreaded use cases.
///
/// As this type does not implement `Drop`, losing the handle to the executor or failing
/// to consistently drive the executor with [`StaticLocalExecutor::tick`] or
/// [`StaticLocalExecutor::run`] will cause the all spawned tasks to permanently leak. Any
/// tasks at the time will not be cancelled.
///
/// [`thread_local]: https://doc.rust-lang.org/std/macro.thread_local.html
#[repr(transparent)]
pub struct StaticLocalExecutor {
state: State,
marker_: PhantomData<UnsafeCell<()>>,
}
impl UnwindSafe for StaticLocalExecutor {}
impl RefUnwindSafe for StaticLocalExecutor {}
impl fmt::Debug for StaticLocalExecutor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
debug_state(&self.state, "StaticLocalExecutor", f)
}
}
impl StaticLocalExecutor {
/// Creates a new StaticLocalExecutor.
///
/// # Examples
///
/// ```
/// use async_executor::StaticLocalExecutor;
///
/// thread_local! {
/// static EXECUTOR: StaticLocalExecutor = StaticLocalExecutor::new();
/// }
/// ```
pub const fn new() -> Self {
Self {
state: State::new(),
marker_: PhantomData,
}
}
/// Spawns a task onto the executor.
///
/// Note: unlike [`LocalExecutor::spawn`], this function requires being called with a `'static`
/// borrow on the executor.
///
/// # Examples
///
/// ```
/// use async_executor::LocalExecutor;
///
/// let ex = LocalExecutor::new().leak();
///
/// let task = ex.spawn(async {
/// println!("Hello world");
/// });
/// ```
pub fn spawn<T: 'static>(&'static self, future: impl Future<Output = T> + 'static) -> Task<T> {
let (runnable, task) = Builder::new()
.propagate_panic(true)
.spawn_local(|()| future, self.schedule());
runnable.schedule();
task
}
/// Spawns a non-`'static` task onto the executor.
///
/// ## Safety
///
/// The caller must ensure that the returned task terminates
/// or is cancelled before the end of 'a.
pub unsafe fn spawn_scoped<'a, T: 'a>(
&'static self,
future: impl Future<Output = T> + 'a,
) -> Task<T> {
// SAFETY:
//
// - `future` is not `Send` but `StaticLocalExecutor` is `!Sync`,
// `try_tick`, `tick` and `run` can only be called from the origin
// thread of the `StaticLocalExecutor`. Similarly, `spawn_scoped` can only
// be called from the origin thread, ensuring that `future` and the executor
// share the same origin thread. The `Runnable` can be scheduled from other
// threads, but because of the above `Runnable` can only be called or
// dropped on the origin thread.
// - `future` is not `'static`, but the caller guarantees that the
// task, and thus its `Runnable` must not live longer than `'a`.
// - `self.schedule()` is `Send`, `Sync` and `'static`, as checked below.
// Therefore we do not need to worry about what is done with the
// `Waker`.
let (runnable, task) = unsafe {
Builder::new()
.propagate_panic(true)
.spawn_unchecked(|()| future, self.schedule())
};
runnable.schedule();
task
}
/// Attempts to run a task if at least one is scheduled.
///
/// Running a scheduled task means simply polling its future once.
///
/// # Examples
///
/// ```
/// use async_executor::LocalExecutor;
///
/// let ex = LocalExecutor::new().leak();
/// assert!(!ex.try_tick()); // no tasks to run
///
/// let task = ex.spawn(async {
/// println!("Hello world");
/// });
/// assert!(ex.try_tick()); // a task was found
/// ```
pub fn try_tick(&self) -> bool {
self.state.try_tick()
}
/// Runs a single task.
///
/// Running a task means simply polling its future once.
///
/// If no tasks are scheduled when this method is called, it will wait until one is scheduled.
///
/// # Examples
///
/// ```
/// use async_executor::LocalExecutor;
/// use futures_lite::future;
///
/// let ex = LocalExecutor::new().leak();
///
/// let task = ex.spawn(async {
/// println!("Hello world");
/// });
/// future::block_on(ex.tick()); // runs the task
/// ```
pub async fn tick(&self) {
self.state.tick().await;
}
/// Runs the executor until the given future completes.
///
/// # Examples
///
/// ```
/// use async_executor::LocalExecutor;
/// use futures_lite::future;
///
/// let ex = LocalExecutor::new().leak();
///
/// let task = ex.spawn(async { 1 + 2 });
/// let res = future::block_on(ex.run(async { task.await * 2 }));
///
/// assert_eq!(res, 6);
/// ```
pub async fn run<T>(&self, future: impl Future<Output = T>) -> T {
self.state.run(future).await
}
/// Returns a function that schedules a runnable task when it gets woken up.
fn schedule(&'static self) -> impl Fn(Runnable) + Send + Sync + 'static {
let state: &'static State = &self.state;
// TODO: If possible, push into the current local queue and notify the ticker.
move |runnable| {
state.queue.push(runnable).unwrap();
state.notify();
}
}
}
impl Default for StaticLocalExecutor {
fn default() -> Self {
Self::new()
}
}