Expand description
Chapter 2: Waiting for another process.
Processes can start other processes and wait for them — the building block
for “do this sub-task, then continue”. In SimPy you yield env.process(...);
in simu, spawn returns a
ProcessHandle which is itself a future: awaiting
it suspends you until the child process finishes and hands you its return
value.
Our car is now electric. After every trip it must charge before it can drive again — and charging is its own process:
use simu::SimEnv;
let mut env = SimEnv::with_seed(42);
let h = env.handle();
env.spawn(async move {
loop {
println!("Start driving at {}", h.now());
h.timeout(2.0).await;
println!("Start charging at {}", h.now());
let hc = h.clone();
let charging = h.spawn(async move {
hc.timeout(5.0).await;
42.0 // a process can return a value, e.g. the kWh charged
});
let kwh = charging.await; // suspend until charging finishes
assert_eq!(kwh, 42.0);
}
});
env.run_until(15.0);Output:
Start driving at 0
Start charging at 2
Start driving at 7
Start charging at 9
Start driving at 14Two details:
- Handles are cheap clones sharing one env; clone freely
(
let hc = h.clone()) whenever a child process needs its own. - If you don’t need the result, just drop the
ProcessHandle— the child keeps running, fire-and-forget.