use std::sync::Arc;
use std::thread;
use std::time;
use wasmtime::*;
const N_THREADS: i32 = 10;
const N_REPS: i32 = 3;
fn main() -> Result<()> {
println!("Initializing...");
let engine = Engine::default();
let module = Module::from_file(&engine, "examples/threads.wat")?;
let mut linker = Linker::new(&engine);
linker.func_wrap("global", "hello", || {
println!("> Hello from {:?}", thread::current().id());
})?;
let linker = Arc::new(linker);
let children = (0..N_THREADS)
.map(|_| {
let engine = engine.clone();
let module = module.clone();
let linker = linker.clone();
thread::spawn(move || {
run(&engine, &module, &linker).expect("Success");
})
})
.collect::<Vec<_>>();
for child in children {
child.join().unwrap();
}
Ok(())
}
fn run(engine: &Engine, module: &Module, linker: &Linker<()>) -> Result<()> {
println!("Instantiating module...");
let mut store = Store::new(&engine, ());
let instance = linker.instantiate(&mut store, module)?;
let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
println!("Executing...");
for _ in 0..N_REPS {
run.call(&mut store, ())?;
thread::sleep(time::Duration::from_millis(100));
}
println!("> Moving {:?} to a new thread", thread::current().id());
let child = thread::spawn(move || run.call(&mut store, ()));
child.join().unwrap()?;
Ok(())
}