xref: /wasmtime-44.0.1/examples/interrupt.rs (revision 331b0dee)
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 anyhow::Result;
7 use wasmtime::*;
8 
9 fn main() -> Result<()> {
10     // Enable interruptable code via `Config` and then create an interrupt
11     // handle which we'll use later to interrupt running code.
12     let engine = Engine::new(Config::new().interruptable(true))?;
13     let mut store = Store::new(&engine, ());
14     let interrupt_handle = store.interrupt_handle()?;
15 
16     // Compile and instantiate a small example with an infinite loop.
17     let module = Module::from_file(&engine, "examples/interrupt.wat")?;
18     let instance = Instance::new(&mut store, &module, &[])?;
19     let run = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
20 
21     // Spin up a thread to send us an interrupt in a second
22     std::thread::spawn(move || {
23         std::thread::sleep(std::time::Duration::from_secs(1));
24         println!("Interrupting!");
25         interrupt_handle.interrupt();
26     });
27 
28     println!("Entering infinite loop ...");
29     let trap = run.call(&mut store, ()).unwrap_err();
30 
31     println!("trap received...");
32     assert!(trap.to_string().contains("wasm trap: interrupt"));
33 
34     Ok(())
35 }
36