From 4282c3fe406eb3dcca8714799a9696aa5801b6d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mockers?= Date: Sun, 1 Dec 2024 21:09:13 +0100 Subject: [PATCH] make example external_source_external_thread deterministic (#16574) # Objective - make example external_source_external_thread deterministic ## Solution - Don't depend on real time --- .../async_tasks/external_source_external_thread.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/examples/async_tasks/external_source_external_thread.rs b/examples/async_tasks/external_source_external_thread.rs index 9dc45f3eb4..92c7c60a82 100644 --- a/examples/async_tasks/external_source_external_thread.rs +++ b/examples/async_tasks/external_source_external_thread.rs @@ -5,14 +5,15 @@ use bevy::prelude::*; use crossbeam_channel::{bounded, Receiver}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; -use std::time::{Duration, Instant}; fn main() { App::new() .add_event::() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) - .add_systems(Update, (read_stream, spawn_text, move_text)) + .add_systems(Update, (spawn_text, move_text)) + .add_systems(FixedUpdate, read_stream) + .insert_resource(Time::::from_seconds(0.5)) .run(); } @@ -25,7 +26,7 @@ struct StreamEvent(u32); fn setup(mut commands: Commands) { commands.spawn(Camera2d); - let (tx, rx) = bounded::(10); + let (tx, rx) = bounded::(1); std::thread::spawn(move || { // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. @@ -33,12 +34,8 @@ fn setup(mut commands: Commands) { loop { // Everything here happens in another thread // This is where you could connect to an external data source - let start_time = Instant::now(); - let duration = Duration::from_secs_f32(rng.gen_range(0.0..0.2)); - while start_time.elapsed() < duration { - // Spinning for 'duration', simulating doing hard work! - } + // This will block until the previous value has been read in system `read_stream` tx.send(rng.gen_range(0..2000)).unwrap(); } });