diff --git a/rust/src/main.rs b/rust/src/main.rs index fecb74a..0c2f5db 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -2,7 +2,7 @@ use std::{ collections::HashMap, fs::File, io::{BufRead, BufReader}, - sync::{Arc, Mutex, MutexGuard}, + sync::{Arc, Mutex}, thread, }; @@ -20,22 +20,19 @@ fn main() { let cores: usize = std::thread::available_parallelism().unwrap().into(); let file = File::open("../measurements.txt").expect("File measurements.txt not found"); - let reader = BufReader::new(file); - let lines = Arc::new(Mutex::new(reader.lines())); let chunk_length = 1_000_000_000 / cores; let mut handles = vec![]; - for _i in 0..cores { + for i in 0..cores { + let reader = BufReader::new(file.try_clone().unwrap()); + let line_chunk = reader.lines().skip(chunk_length * i).take(chunk_length); let stations_clone = stations.clone(); - let lines_clone = lines.clone(); let handle = thread::spawn(move || { - let lines_guard = lines_clone.lock().unwrap(); - let chunk = lines_guard.take(chunk_length); - lines_guard.skip(chunk_length); - for line_result in chunk { - let line = line_result.expect("could not read line"); - let (station, temp) = line.split_once(';').unwrap(); - let temp = temp.parse().unwrap(); - let mut stations_guard = stations_clone.lock().unwrap(); + for line in line_chunk { + let line = line.expect("could not read line"); + println!("Thread #{i}: {line}"); + let (station, temp) = line.split_once(';').expect("Error while splitting"); + let temp = temp.parse().expect("Error while parsing temperature"); + let mut stations_guard = stations_clone.lock().expect("Error while locking thread"); let measurements_option = stations_guard.get_mut(station); if let Some(measurements) = measurements_option { if temp < measurements.min { @@ -52,10 +49,7 @@ fn main() { count: 1, sum: temp, }; - stations_clone - .lock() - .unwrap() - .insert(station.to_owned(), measurements); + stations_guard.insert(station.to_owned(), measurements); } } });