added mulitthreaded file reading

This commit is contained in:
Sven Vogel 2023-05-31 09:46:08 +02:00
parent 51e769be91
commit 9ac25c5558
4 changed files with 43 additions and 0 deletions

8
threads/Cargo.toml Normal file
View File

@ -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]

1
threads/res/1.txt Normal file
View File

@ -0,0 +1 @@
af uafi spdh has gh kajs

1
threads/res/2.txt Normal file
View File

@ -0,0 +1 @@
tj ah ldsh lkjhasl jkasl

33
threads/src/main.rs Normal file
View File

@ -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();
}