From ebf81c609ff764ebc0eefa21b764970a9ba240e3 Mon Sep 17 00:00:00 2001 From: BD103 <59022059+BD103@users.noreply.github.com> Date: Tue, 13 Feb 2024 21:29:26 -0500 Subject: [PATCH] Use `std::thread::sleep` instead of spin-waiting in the async_compute example (#11856) # Objective - The [`async_compute` example](https://github.com/bevyengine/bevy/blob/77c26f64ce0c1a538629a544b7020eb2d2b77466/examples/async_tasks/async_compute.rs#L65-L68) uses a busy loop. - It's good practice to mark busy loops with the [`std::hint::spin_loop`](https://doc.rust-lang.org/stable/std/hint/fn.spin_loop.html) function. ## Solution - Call [`std::hint::spin_loop`](https://doc.rust-lang.org/stable/std/hint/fn.spin_loop.html) within the busy loop. ## Discussion - While it is good practice to mark busy loops with `spin_loop`, it does somewhat increase cognitive complexity. Since it is an example, it does not matter too much. - This is somewhat mitigated by the fact that it is within [`std::hint`](https://doc.rust-lang.org/stable/std/hint/index.html), which only affects compilation and doesn't do anything. - Should I add a comment on what `spin_loop` does? - Should the `while` loop just be replaced with `std::thread::sleep`? --- examples/async_tasks/async_compute.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/examples/async_tasks/async_compute.rs b/examples/async_tasks/async_compute.rs index 60d2eba88a..134373bc36 100644 --- a/examples/async_tasks/async_compute.rs +++ b/examples/async_tasks/async_compute.rs @@ -7,7 +7,7 @@ use bevy::{ tasks::{block_on, futures_lite::future, AsyncComputeTaskPool, Task}, }; use rand::Rng; -use std::time::{Duration, Instant}; +use std::{thread, time::Duration}; fn main() { App::new() @@ -60,12 +60,11 @@ fn spawn_tasks(mut commands: Commands) { let entity = commands.spawn_empty().id(); let task = thread_pool.spawn(async move { let mut rng = rand::thread_rng(); - let start_time = Instant::now(); + let duration = Duration::from_secs_f32(rng.gen_range(0.05..0.2)); - while start_time.elapsed() < duration { - // Spinning for 'duration', simulating doing hard - // compute work generating translation coords! - } + + // Pretend this is a time-intensive function. :) + thread::sleep(duration); // Such hard work, all done! let transform = Transform::from_xyz(x as f32, y as f32, z as f32);