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