busy_behavior/
busy_behavior.rs

1//! This sample demonstrates creating a thread pool with 4 tasks and spawning 40 tasks that spin
2//! for 100ms. It's expected to take about a second to run (assuming the machine has >= 4 logical
3//! cores)
4
5#![expect(clippy::print_stdout, reason = "Allowed in examples.")]
6
7use bevy_platform::time::Instant;
8use bevy_tasks::TaskPoolBuilder;
9use core::time::Duration;
10
11fn main() {
12    let pool = TaskPoolBuilder::new()
13        .thread_name("Busy Behavior ThreadPool".to_string())
14        .num_threads(4)
15        .build();
16
17    let t0 = Instant::now();
18    pool.scope(|s| {
19        for i in 0..40 {
20            s.spawn(async move {
21                let now = Instant::now();
22                while Instant::now() - now < Duration::from_millis(100) {
23                    // spin, simulating work being done
24                }
25
26                println!(
27                    "Thread {:?} index {} finished",
28                    std::thread::current().id(),
29                    i
30                );
31            });
32        }
33    });
34
35    let t1 = Instant::now();
36    println!("all tasks finished in {} secs", (t1 - t0).as_secs_f32());
37}