From 4717dbdf629cefc7dc840d87de8e0ed425b12c7a Mon Sep 17 00:00:00 2001 From: Spaceface16518 Date: Mon, 23 Nov 2020 13:03:39 -0600 Subject: [PATCH] remove tokio dependency Substituted with a manually chunked std::thread approach --- Cargo.toml | 2 +- src/main.rs | 56 ++++++++++++++++++++++++++--------------------------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8d82553..a7d92a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,6 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -tokio = { version = "0.3", features = ["full"] } image = "0.23.12" rand = "0.7.3" +num_cpus = "1.13.0" diff --git a/src/main.rs b/src/main.rs index 0c8ed6e..1a1fba0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,8 @@ mod color; use image; use rand::{thread_rng, Rng}; -use tokio::sync::mpsc; +use std::sync::mpsc; +use std::thread; const WIDTH: u32 = 1024; const HEIGHT: u32 = 1024; @@ -11,39 +12,38 @@ const NB_SAMPLES: u32 = 50; const SIZE: f64 = 0.000000001; const MAX_ITER: u32 = 1000; -#[tokio::main] -async fn main() { - let blocking_task = tokio::spawn(async { - let px: f64 = -0.5557506; - let py: f64 = -0.55560; - let mut buf: Vec = Vec::with_capacity(BUF_SIZE as usize); - buf.resize(BUF_SIZE as usize, 0); +fn main() { + let px: f64 = -0.5557506; + let py: f64 = -0.55560; + let mut buf: Vec = vec![0; BUF_SIZE as usize]; - let (tx, mut rx) = mpsc::channel(100); + let (tx, rx) = mpsc::sync_channel(100); - for y in 0..HEIGHT { - let tx = tx.clone(); - tokio::spawn(async move { + let chunk_size = HEIGHT / num_cpus::get() as u32; + for offset in (0..HEIGHT).step_by(chunk_size as usize) { + let tx = tx.clone(); + thread::spawn(move || { + // let (line, line_number) = render_line(y, px, py); + // tx.send((line, line_number)).await.unwrap(); + for y in offset..offset + chunk_size { let (line, line_number) = render_line(y, px, py); - tx.send((line, line_number)).await.unwrap(); - }); - } - - drop(tx); + tx.send((line, line_number)).unwrap(); + } + }); + } - let mut finished: f64 = 0.; - while let Some(res) = rx.recv().await { - finished += 1.; - let percentage_finished = (finished / (HEIGHT as f64)) * 100.; - print!("Progress: {}%\r", percentage_finished as u32); + drop(tx); - let (line, line_number) = res; - write_line(&mut buf, &line, line_number); - } - image::save_buffer("fractal.png", &buf, WIDTH, HEIGHT, image::ColorType::Rgb8).unwrap(); - }); + let mut finished: f64 = 0.; + for res in rx.iter() { + finished += 1.; + let percentage_finished = (finished / (HEIGHT as f64)) * 100.; + print!("Progress: {}%\r", percentage_finished as u32); - blocking_task.await.unwrap(); + let (line, line_number) = res; + write_line(&mut buf, &line, line_number); + } + image::save_buffer("fractal.png", &buf, WIDTH, HEIGHT, image::ColorType::Rgb8).unwrap(); } fn write_line(buf: &mut Vec, line: &Vec, line_number: u32) {