Skip to main content

Module ch01_basic_concepts

Module ch01_basic_concepts 

Source
Expand description

Chapter 1: Basic concepts — processes, timeouts, and the clock.

A discrete-event simulation models a system as processes that do something, wait, and do something again. While a process waits, simulated time jumps directly to the next interesting moment — nothing “runs” in between, which is why a simulated year can take milliseconds of wall-clock time.

In simu, a process is an ordinary async block. Waiting is .awaiting a Timeout: the executor suspends the process and resumes it when the simulated clock reaches the deadline. There is no tokio and no threads — one SimEnv owns the clock and drives everything.

Our first process models a car that alternately parks and drives:

use simu::SimEnv;

let mut env = SimEnv::with_seed(42);
let h = env.handle(); // cheap Clone handle, moved into the process

env.spawn(async move {
    loop {
        println!("Start parking at {}", h.now());
        h.timeout(5.0).await; // park for 5 time units

        println!("Start driving at {}", h.now());
        h.timeout(2.0).await; // drive for 2 time units
    }
});

env.run_until(15.0); // drive the event loop until t = 15
assert_eq!(env.now(), 15.0);

Output:

Start parking at 0
Start driving at 5
Start parking at 7
Start driving at 12
Start parking at 14

Things worth noticing:

  • SimEnv::with_seed makes the run reproducible; same seed + same logic = identical results, always.
  • The process gets an EnvHandle (env.handle()), not the env itself: the env stays outside driving the loop, the handle goes inside for now() / timeout() / spawn().
  • The process loops forever; that is fine. run_until stops the world at t = 15, and dropping the env reclaims the still-suspended process.
  • Time is f64 and unit-less — you decide whether 1.0 means a second or a day.