Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make example external_source_external_thread deterministic #16574

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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