Created
September 7, 2022 02:08
-
-
Save jtt9340/e6004b431af3521ddf083054d4d3f233 to your computer and use it in GitHub Desktop.
A port of the "concurrent pi" Go example to both native threads and futures in Rust
This file contains 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
use std::time::Instant; | |
use std::thread; | |
use std::sync::mpsc::channel; | |
use async_std::task; | |
use async_std::channel::unbounded; | |
const NUM_ITERATIONS: u32 = 5000; | |
#[allow(unused_variables)] | |
async fn async_pi(n: u32) -> f64 { | |
use async_std::channel::Sender; | |
async fn term(ch: Sender<f64>, k: u32) { | |
ch.send((4 * (-1i32).pow(k)) as f64 / (2 * k + 1) as f64).await.unwrap(); | |
} | |
let (tx, rx) = unbounded(); | |
for k in 0..=n { | |
let tx = tx.clone(); | |
task::spawn(term(tx, k)); | |
} | |
let mut f = 0.0; | |
for k in 0..=n { | |
f += rx.recv().await.unwrap(); | |
} | |
f | |
} | |
#[allow(unused_variables)] | |
fn threaded_pi(n: u32) -> f64 { | |
use std::sync::mpsc::Sender; | |
fn term(ch: Sender<f64>, k: u32) { | |
ch.send((4 * (-1i32).pow(k)) as f64 / (2 * k + 1) as f64).unwrap(); | |
} | |
let (tx, rx) = channel(); | |
for k in 0..=n { | |
let tx = tx.clone(); | |
thread::spawn(move || term(tx, k)); | |
} | |
let mut f = 0.0; | |
for k in 0..=n { | |
f += rx.recv().unwrap(); | |
} | |
f | |
} | |
fn main() { | |
let threaded_thread = thread::spawn(move || { | |
let start = Instant::now(); | |
let pi = threaded_pi(NUM_ITERATIONS); | |
println!("Took {} seconds to approximate pi ({}) using threads", start.elapsed().as_secs(), pi); | |
}); | |
let task_thread = thread::spawn(move || { | |
let start = Instant::now(); | |
let pi = task::block_on(async_pi(NUM_ITERATIONS)); | |
println!("Took {} seconds to approximate pi ({}) using futures", start.elapsed().as_secs(), pi); | |
}); | |
threaded_thread.join().unwrap(); | |
task_thread.join().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment