Are there any examples of using std::sync::future
? I have not found any anywhere.
Thanks!
Are there any examples of using std::sync::future
? I have not found any anywhere.
Thanks!
OK, here is a parallel Fibonacci function which works OK on n = 30
, but eats extremely much memory on n = 42
. Any ideas? Is it a not idiomatic use of Future
s?
use std::sync::*;
fn sfib(n: i32) -> i32 {
match n {
0 | 1 | 2 => n,
_ => sfib (n-1) + sfib(n-2)
}
}
pub fn fib(n: i32) -> Future<i32> {
Future::spawn(move || {
if n < 13 { sfib(n) }
else {
let mut n2f = fib(n - 2);
let n1 = fib(n - 1).get();
let n2 = n2f.get();
n1 + n2
}
})
}
You're not caching the results, each call of fib
spawns two which also call fib
twice, resulting in exponential memory and time use.
I think this is not a good use of Futures. The calculation of an nth Fibonacci number is not parallelizable and your code is run synchronously anyway, the call to "get" blocks so you would be better running the whole calculation in a single thread without adding the overhead of a Future in each recursive call.
For this particular problem, you can just wrap the call to "sfib" in a Future and do something else while the nth Fibonacci is calculated.
As @tbu said, you can optimize "sfib" by applying memoization.