mirror of
https://github.com/bevyengine/bevy
synced 2024-11-10 07:04:33 +00:00
Use std:🧵:sleep
instead of spin-waiting in the async_compute example (#11856)
# Objective
- The [`async_compute`
example](77c26f64ce/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:🧵:sleep`?
This commit is contained in:
parent
73bf730da9
commit
ebf81c609f
1 changed files with 5 additions and 6 deletions
|
@ -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);
|
||||
|
|
Loading…
Reference in a new issue