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

  1. #![allow(unused)]
  2. fn main() {
  3. // create a Config context
  4. let mut config = Config::create()?;
  5. config.bulk_memory_operations(true);
  6. // create a Store context
  7. let mut store = Store::create()?;
  8. // create a Vm context with the given Config and Store
  9. let mut vm = Vm::create(Some(config), Some(&mut store))?;
  10. // register a wasm module from a wasm file
  11. let file = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
  12. .join("bindings/rust/wasmedge-sys/tests/data/fibonacci.wasm");
  13. vm.register_wasm_from_file("extern", file)?;
  14. }

Step 2: create two child threads to compute Fib(4) and Fib(5) respectively

  1. #![allow(unused)]
  2. fn main() {
  3. let vm = Arc::new(Mutex::new(vm));
  4. // compute fib(4) by a child thread
  5. let vm_cloned = Arc::clone(&vm);
  6. let handle_a = thread::spawn(move || {
  7. let vm_child_thread = vm_cloned.lock().expect("fail to lock vm");
  8. let returns = vm_child_thread
  9. .run_registered_function("extern", "fib", [WasmValue::from_i32(4)])
  10. .expect("fail to compute fib(4)");
  11. let fib4 = returns[0].to_i32();
  12. println!("fib(4) by child thread: {}", fib4);
  13. fib4
  14. });
  15. // compute fib(5) by a child thread
  16. let vm_cloned = Arc::clone(&vm);
  17. let handle_b = thread::spawn(move || {
  18. let vm_child_thread = vm_cloned.lock().expect("fail to lock vm");
  19. let returns = vm_child_thread
  20. .run_registered_function("extern", "fib", [WasmValue::from_i32(5)])
  21. .expect("fail to compute fib(5)");
  22. let fib5 = returns[0].to_i32();
  23. println!("fib(5) by child thread: {}", fib5);
  24. fib5
  25. });
  26. }

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.