From 95edd2ea7145181c13a4f40ee176d70fc88cab73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mockers?= Date: Thu, 6 Jun 2024 02:21:33 +0200 Subject: [PATCH] async_compute example: don't block in the task (#13699) # Objective - Fixes #13672 ## Solution - Don't use blocking sleep in the tasks, so that it won't block the task pool --- Cargo.toml | 1 + examples/async_tasks/async_compute.rs | 8 +++----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9d06f9868c..c59b9bc758 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -354,6 +354,7 @@ serde = { version = "1", features = ["derive"] } bytemuck = "1.7" # Needed to poll Task examples futures-lite = "2.0.1" +async-std = "1.12" crossbeam-channel = "0.5.0" argh = "0.1.12" thiserror = "1.0" diff --git a/examples/async_tasks/async_compute.rs b/examples/async_tasks/async_compute.rs index bf4b8a26ec..563b9e4e4c 100644 --- a/examples/async_tasks/async_compute.rs +++ b/examples/async_tasks/async_compute.rs @@ -8,7 +8,7 @@ use bevy::{ tasks::{block_on, futures_lite::future, AsyncComputeTaskPool, Task}, }; use rand::Rng; -use std::{thread, time::Duration}; +use std::time::Duration; fn main() { App::new() @@ -60,12 +60,10 @@ fn spawn_tasks(mut commands: Commands) { // spawn() can be used to poll for the result let entity = commands.spawn_empty().id(); let task = thread_pool.spawn(async move { - let mut rng = rand::thread_rng(); - - let duration = Duration::from_secs_f32(rng.gen_range(0.05..0.2)); + let duration = Duration::from_secs_f32(rand::thread_rng().gen_range(0.05..5.0)); // Pretend this is a time-intensive function. :) - thread::sleep(duration); + async_std::task::sleep(duration).await; // Such hard work, all done! let transform = Transform::from_xyz(x as f32, y as f32, z as f32);