Files
wasmtime/examples/interrupt.rs
Alex Crichton 7a1b7cdf92 Implement RFC 11: Redesigning Wasmtime's APIs (#2897)
Implement Wasmtime's new API as designed by RFC 11. This is quite a large commit which has had lots of discussion externally, so for more information it's best to read the RFC thread and the PR thread.
2021-06-03 09:10:53 -05:00

36 lines
1.3 KiB
Rust

//! Small example of how you can interrupt the execution of a wasm module to
//! ensure that it doesn't run for too long.
// You can execute this example with `cargo run --example interrupt`
use anyhow::Result;
use wasmtime::*;
fn main() -> Result<()> {
// Enable interruptable code via `Config` and then create an interrupt
// handle which we'll use later to interrupt running code.
let engine = Engine::new(Config::new().interruptable(true))?;
let mut store = Store::new(&engine, ());
let interrupt_handle = store.interrupt_handle()?;
// Compile and instantiate a small example with an infinite loop.
let module = Module::from_file(&engine, "examples/interrupt.wat")?;
let instance = Instance::new(&mut store, &module, &[])?;
let run = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
// Spin up a thread to send us an interrupt in a second
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(1));
println!("Interrupting!");
interrupt_handle.interrupt();
});
println!("Entering infinite loop ...");
let trap = run.call(&mut store, ()).unwrap_err();
println!("trap received...");
assert!(trap.to_string().contains("wasm trap: interrupt"));
Ok(())
}