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 epoch interruption code via `Config` which means that code will 11 // get interrupted when `Engine::increment_epoch` happens. 12 let engine = Engine::new(Config::new().epoch_interruption(true))?; 13 let mut store = Store::new(&engine, ()); 14 store.set_epoch_deadline(1); 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 engine.increment_epoch(); 26 }); 27 28 println!("Entering infinite loop ..."); 29 let trap = run.call(&mut store, ()).unwrap_err(); 30 31 println!("trap received..."); 32 assert!(trap.trap_code().unwrap() == TrapCode::Interrupt); 33 34 Ok(()) 35 } 36