Path: blob/main/crates/bevy_tasks/src/thread_executor.rs
6604 views
use core::marker::PhantomData;1use std::thread::{self, ThreadId};23use crate::executor::Executor;4use async_task::Task;5use futures_lite::Future;67/// An executor that can only be ticked on the thread it was instantiated on. But8/// can spawn `Send` tasks from other threads.9///10/// # Example11/// ```12/// # use std::sync::{Arc, atomic::{AtomicI32, Ordering}};13/// use bevy_tasks::ThreadExecutor;14///15/// let thread_executor = ThreadExecutor::new();16/// let count = Arc::new(AtomicI32::new(0));17///18/// // create some owned values that can be moved into another thread19/// let count_clone = count.clone();20///21/// std::thread::scope(|scope| {22/// scope.spawn(|| {23/// // we cannot get the ticker from another thread24/// let not_thread_ticker = thread_executor.ticker();25/// assert!(not_thread_ticker.is_none());26///27/// // but we can spawn tasks from another thread28/// thread_executor.spawn(async move {29/// count_clone.fetch_add(1, Ordering::Relaxed);30/// }).detach();31/// });32/// });33///34/// // the tasks do not make progress unless the executor is manually ticked35/// assert_eq!(count.load(Ordering::Relaxed), 0);36///37/// // tick the ticker until task finishes38/// let thread_ticker = thread_executor.ticker().unwrap();39/// thread_ticker.try_tick();40/// assert_eq!(count.load(Ordering::Relaxed), 1);41/// ```42#[derive(Debug)]43pub struct ThreadExecutor<'task> {44executor: Executor<'task>,45thread_id: ThreadId,46}4748impl<'task> Default for ThreadExecutor<'task> {49fn default() -> Self {50Self {51executor: Executor::new(),52thread_id: thread::current().id(),53}54}55}5657impl<'task> ThreadExecutor<'task> {58/// create a new [`ThreadExecutor`]59pub fn new() -> Self {60Self::default()61}6263/// Spawn a task on the thread executor64pub fn spawn<T: Send + 'task>(65&self,66future: impl Future<Output = T> + Send + 'task,67) -> Task<T> {68self.executor.spawn(future)69}7071/// Gets the [`ThreadExecutorTicker`] for this executor.72/// Use this to tick the executor.73/// It only returns the ticker if it's on the thread the executor was created on74/// and returns `None` otherwise.75pub fn ticker<'ticker>(&'ticker self) -> Option<ThreadExecutorTicker<'task, 'ticker>> {76if thread::current().id() == self.thread_id {77return Some(ThreadExecutorTicker {78executor: self,79_marker: PhantomData,80});81}82None83}8485/// Returns true if `self` and `other`'s executor is same86pub fn is_same(&self, other: &Self) -> bool {87core::ptr::eq(self, other)88}89}9091/// Used to tick the [`ThreadExecutor`]. The executor does not92/// make progress unless it is manually ticked on the thread it was93/// created on.94#[derive(Debug)]95pub struct ThreadExecutorTicker<'task, 'ticker> {96executor: &'ticker ThreadExecutor<'task>,97// make type not send or sync98_marker: PhantomData<*const ()>,99}100101impl<'task, 'ticker> ThreadExecutorTicker<'task, 'ticker> {102/// Tick the thread executor.103pub async fn tick(&self) {104self.executor.executor.tick().await;105}106107/// Synchronously try to tick a task on the executor.108/// Returns false if does not find a task to tick.109pub fn try_tick(&self) -> bool {110self.executor.executor.try_tick()111}112}113114#[cfg(test)]115mod tests {116use super::*;117use alloc::sync::Arc;118119#[test]120fn test_ticker() {121let executor = Arc::new(ThreadExecutor::new());122let ticker = executor.ticker();123assert!(ticker.is_some());124125thread::scope(|s| {126s.spawn(|| {127let ticker = executor.ticker();128assert!(ticker.is_none());129});130});131}132}133134135