From 9ac25c555821a2b90f6a48d1aba38560e343989d Mon Sep 17 00:00:00 2001 From: teridax Date: Wed, 31 May 2023 09:46:08 +0200 Subject: [PATCH] added mulitthreaded file reading --- threads/Cargo.toml | 8 ++++++++ threads/res/1.txt | 1 + threads/res/2.txt | 1 + threads/src/main.rs | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 43 insertions(+) create mode 100644 threads/Cargo.toml create mode 100644 threads/res/1.txt create mode 100644 threads/res/2.txt create mode 100644 threads/src/main.rs diff --git a/threads/Cargo.toml b/threads/Cargo.toml new file mode 100644 index 0000000..a40fcd5 --- /dev/null +++ b/threads/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "threads" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/threads/res/1.txt b/threads/res/1.txt new file mode 100644 index 0000000..0a6a5e8 --- /dev/null +++ b/threads/res/1.txt @@ -0,0 +1 @@ +af uafi spdh has gh kajs \ No newline at end of file diff --git a/threads/res/2.txt b/threads/res/2.txt new file mode 100644 index 0000000..4e86a8a --- /dev/null +++ b/threads/res/2.txt @@ -0,0 +1 @@ +tj ah ldsh lkjhasl jkasl \ No newline at end of file diff --git a/threads/src/main.rs b/threads/src/main.rs new file mode 100644 index 0000000..31a2bf0 --- /dev/null +++ b/threads/src/main.rs @@ -0,0 +1,33 @@ +use std::{thread, sync::mpsc}; + +fn main() { + let (path_send, path_recv) = mpsc::channel(); + let (count_send, count_recv) = mpsc::channel(); + + let handle = thread::spawn(move || { + for path in path_recv.iter() { + if let Ok(source) = std::fs::read_to_string(&path) { + let words = source.split_whitespace().filter(|ws| !ws.is_empty()).count(); + count_send.send(format!("path: {} words: {words}", &path)).unwrap(); + } else { + drop(count_send); + break; + } + } + }); + + loop { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf).expect("unable to read from stdin"); + + if let Err(_) = path_send.send(String::from(buf.trim())) { + break; + } + } + + count_recv.try_iter().for_each(|c| { + println!("{c}"); + }); + + handle.join().unwrap(); +}