Skip to content

Commit

Permalink
Use std::thread::sleep instead of spin-waiting in the async_compute…
Browse files Browse the repository at this point in the history
… 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`?
  • Loading branch information
BD103 authored Feb 14, 2024
1 parent 73bf730 commit ebf81c6
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions examples/async_tasks/async_compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit ebf81c6

Please sign in to comment.