Rust multi-threading
Let’s get on with Day5.
In general need functions that will either give first half of the range or bottom half.
Once there is only single element to be returned, the range contains same element in both upper and lower elements.
For the first 7 characters, we start with a tuple(0,127)
For the last 3 characters,we start with tuple (0,8)
We will have two threads apart from the main one like below
There will be two channels, let’s see if that works.
Initially trying with main thread reading the file was not working since it would exit after sending the first record, not sure why.
So created three threads, one reads file lines and sends it to second thread
-- snip --
let handle1 = thread::spawn(move || {
if let Ok(lines) = read_lines("./input.txt") {
// Consumes the iterator, returns an (Optional) String
for line in lines {
tx.send(line.unwrap()).unwrap();
//thread::sleep(Duration::from_secs(2));
}
}
});
-- snip --
which calculates the seat id and sends this to third thread
-- snip --
let handle2 = thread::spawn(move || {
for received in rx {
// println!("Got: {}", received);
let seat: u32 = get_seat_id(received);
tx1.send(seat).unwrap();
}
});
-- snip --
which tracks the global maximum.
-- snip --
let handle3 = thread::spawn(move || {
for seat_id in rx1 {
println!("Got: {}", seat_id);
unsafe {
if seat_id>max {
max = seat_id;
}
}
}
});
-- snip --
Once all threads finish, the max value is printed.
I don’t really think there is some huge parallelism going on here.
But, was fun.
Code here : https://github.com/aksharau/RustyAdventOfCode/blob/main/Day5/part1.rs
References: