Skip to content

Commit

Permalink
make example external_source_external_thread deterministic (#16574)
Browse files Browse the repository at this point in the history
# Objective

- make example external_source_external_thread deterministic

## Solution

- Don't depend on real time
  • Loading branch information
mockersf authored Dec 1, 2024
1 parent 2309c07 commit 4282c3f
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions examples/async_tasks/external_source_external_thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<StreamEvent>()
.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::<Fixed>::from_seconds(0.5))
.run();
}

Expand All @@ -25,20 +26,16 @@ struct StreamEvent(u32);
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);

let (tx, rx) = bounded::<u32>(10);
let (tx, rx) = bounded::<u32>(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.
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
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();
}
});
Expand Down

0 comments on commit 4282c3f

Please sign in to comment.