Compute Fibonacci numbers concurrently
Overview
In this example, we will demonstrate how to use the objects and the APIs defined in wasmedge-sys
to compute Fibonacci numbers concurrently. we creates two child threads, thread_a
and thread_b
, which are responsible 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
.
The code in the example is verified on
- wasmedge-sys v0.10.0
- wasmedge-types v0.3.0
Step 1: create a Vm context and register the WebAssembly module
Step 2: create two child threads to compute Fib(4)
and Fib(5)
respectively
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 in threads.rs.