Created
October 27, 2017 21:26
-
-
Save mre/d7a893e80765fc8fe60402cd63b58790 to your computer and use it in GitHub Desktop.
Fibonacci Parallel Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extern crate threadpool; | |
| extern crate num_cpus; | |
| use threadpool::ThreadPool; | |
| use std::sync::mpsc::channel; | |
| fn fib_real(number: u64) -> u64 { | |
| match number < 2 { | |
| true => number, | |
| false => run(number - 1) + run(number - 2), | |
| } | |
| } | |
| struct FibonacciPool { | |
| pool: threadpool::ThreadPool, | |
| } | |
| impl Fibonacci { | |
| fn new() -> Self { | |
| let pool = ThreadPool::new(num_cpus::get()); | |
| Fibonacci { | |
| pool } | |
| } | |
| fn run(&self, number: u64) -> u64 { | |
| let (tx, rx) = channel(); | |
| let tx = tx.clone(); | |
| self.pool.execute(move || { | |
| tx.send(self.fib_real(number - 1)).expect("Could not send data!"); | |
| }); | |
| let tx = tx.clone(); | |
| self.pool.execute(move || { | |
| tx.send(self.fib_real(number - 2)).expect("Could not send data!"); | |
| }); | |
| rx.iter().take(2).fold(0, |a, b| a + b) | |
| } | |
| } | |
| fn main() { | |
| let fibonacci = FibonacciPool::new(); | |
| println!("{}", fibonacci.run(50)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment