Still broken but it compiles. For some reason lines are not properly being read and only one thread is being run

This commit is contained in:
Fabian Schmidt 2024-04-29 16:24:08 +02:00
parent 180da512f6
commit 18ea81eaaa

View File

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