xref: /wasmtime-44.0.1/examples/interrupt.rs (revision 9ce3ffe1)
1c9a0ba81SAlex Crichton //! Small example of how you can interrupt the execution of a wasm module to
2c9a0ba81SAlex Crichton //! ensure that it doesn't run for too long.
3c9a0ba81SAlex Crichton 
4c9a0ba81SAlex Crichton // You can execute this example with `cargo run --example interrupt`
5c9a0ba81SAlex Crichton 
6c9a0ba81SAlex Crichton use wasmtime::*;
7c9a0ba81SAlex Crichton 
main() -> Result<()>8c9a0ba81SAlex Crichton fn main() -> Result<()> {
9c22033bfSAlex Crichton     // Enable epoch interruption code via `Config` which means that code will
10c22033bfSAlex Crichton     // get interrupted when `Engine::increment_epoch` happens.
11c22033bfSAlex Crichton     let engine = Engine::new(Config::new().epoch_interruption(true))?;
127a1b7cdfSAlex Crichton     let mut store = Store::new(&engine, ());
13c22033bfSAlex Crichton     store.set_epoch_deadline(1);
14c9a0ba81SAlex Crichton 
15c9a0ba81SAlex Crichton     // Compile and instantiate a small example with an infinite loop.
1615c68f2cSYury Delendik     let module = Module::from_file(&engine, "examples/interrupt.wat")?;
177a1b7cdfSAlex Crichton     let instance = Instance::new(&mut store, &module, &[])?;
18*b0939f66SAlex Crichton     let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
19c9a0ba81SAlex Crichton 
20c9a0ba81SAlex Crichton     // Spin up a thread to send us an interrupt in a second
21c9a0ba81SAlex Crichton     std::thread::spawn(move || {
22c9a0ba81SAlex Crichton         std::thread::sleep(std::time::Duration::from_secs(1));
23c9a0ba81SAlex Crichton         println!("Interrupting!");
24c22033bfSAlex Crichton         engine.increment_epoch();
25c9a0ba81SAlex Crichton     });
26c9a0ba81SAlex Crichton 
27c9a0ba81SAlex Crichton     println!("Entering infinite loop ...");
282afaac51SAlex Crichton     let err = run.call(&mut store, ()).unwrap_err();
29c9a0ba81SAlex Crichton 
30c9a0ba81SAlex Crichton     println!("trap received...");
312afaac51SAlex Crichton     assert_eq!(err.downcast::<Trap>()?, Trap::Interrupt);
32c9a0ba81SAlex Crichton 
33c9a0ba81SAlex Crichton     Ok(())
34c9a0ba81SAlex Crichton }
35