Compute Fibonacci numbers concurrently
Prerequisites
This example uses the following crates:
- wasmedge-sys v0.7.0
- wasmedge-types v0.1.1
Overview
In this example, we will demonstrate how to use the objects and the APIs defined in wasmedge-sys to compute Fibonacci numbers concurrently.
Example
In the following code, we creates two child threads, thread_a and thread_b, which are responsbile for compute Fib(4) and Fib(5) by calling the host function fib, respectively. After that, the main thread computes Fib(6) by adding the numbers returned by thread_a and thread_b.
Step 1: create a Vm context and register the WebAssembly module
2. #![allow(unused)]
3. fn main() {
4. // create a Config context
5. let mut config = Config::create()?;
6. config.bulk_memory_operations(true);
8. // create a Store context
9. let mut store = Store::create()?;
11. // create a Vm context with the given Config and Store
12. let mut vm = Vm::create(Some(config), Some(&mut store))?;
14. // register a wasm module from a wasm file
15. let file = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
16. .join("bindings/rust/wasmedge-sys/tests/data/fibonacci.wasm");
17. vm.register_wasm_from_file("extern", file)?;
18. }
Step 2: create two child threads to compute Fib(4) and Fib(5) respectively
2. #![allow(unused)]
3. fn main() {
4. let vm = Arc::new(Mutex::new(vm));
6. // compute fib(4) by a child thread
7. let vm_cloned = Arc::clone(&vm);
8. let handle_a = thread::spawn(move || {
9. let vm_child_thread = vm_cloned.lock().expect("fail to lock vm");
10. let returns = vm_child_thread
11. .run_registered_function("extern", "fib", [WasmValue::from_i32(4)])
12. .expect("fail to compute fib(4)");
14. let fib4 = returns[0].to_i32();
15. println!("fib(4) by child thread: {}", fib4);
17. fib4
18. });
20. // compute fib(5) by a child thread
21. let vm_cloned = Arc::clone(&vm);
22. let handle_b = thread::spawn(move || {
23. let vm_child_thread = vm_cloned.lock().expect("fail to lock vm");
24. let returns = vm_child_thread
25. .run_registered_function("extern", "fib", [WasmValue::from_i32(5)])
26. .expect("fail to compute fib(5)");
28. let fib5 = returns[0].to_i32();
29. println!("fib(5) by child thread: {}", fib5);
31. fib5
32. });
34. }
Step3: Get the returns from the two child threads, and compute Fib(6)
let fib4 = handle_a.join().unwrap(); let fib5 = handle_b.join().unwrap(); // compute fib(6) println!("fib(6) = fib(5) + fib(1) = {}", fib5 + fib4);
The final result of the code above should be printed on the screen like below:
fib(4) by child thread: 5 fib(5) by child thread: 8 fib(6) = fib(5) + fib(1) = 13
The complete code in this demo can be found on WasmEdge Github.
