multithread

This commit is contained in:
Daniel Bulant 2023-12-17 15:30:02 +01:00
parent 825238d105
commit ec8ec31063
2 changed files with 40 additions and 16 deletions

View file

@ -2,7 +2,14 @@
name = "sixteenth" name = "sixteenth"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
[profile.release]
opt-level = 3
[target.x86_64-unknown-linux-gnu]
rustflags = [
"-C", "target-feature=+crt-static"
]

View file

@ -1,4 +1,4 @@
use std::{fs::File, io::{BufReader, BufRead, Write}, ops::Add, fmt::Debug, hash::Hasher}; use std::{fs::File, io::{BufReader, BufRead, Write}, ops::Add, fmt::Debug, hash::Hasher, sync::Arc};
fn main() { fn main() {
part1(); part1();
@ -294,21 +294,38 @@ fn part1() {
fn part2() { fn part2() {
let (max_point, rows, columns) = setup(); let (max_point, rows, columns) = setup();
let mut count = 0; let mut threads = Vec::with_capacity(4);
let rows = Arc::new(rows);
let columns = Arc::new(columns);
for vector in [VEC_LEFT, VEC_RIGHT, VEC_UP, VEC_DOWN] { for vector in [VEC_LEFT, VEC_RIGHT, VEC_UP, VEC_DOWN] {
let is_vert = vector.is_vertical(); let rows = rows.clone();
let is_pos = vector.is_positive(); let columns = columns.clone();
let num2 = if !is_pos { max_point.x - 1 } else { 0 }; threads.push(
for num in 0..max_point.x { std::thread::spawn(move || {
let beam = Beam { let mut count = 0;
point: if is_vert { Point { x: num, y: num2 } } else { Point { x: num2, y: num } }, let is_vert = vector.is_vertical();
vector let is_pos = vector.is_positive();
}; let num2 = if !is_pos { max_point.x - 1 } else { 0 };
let count_here = get_count(max_point, &rows, &columns, beam); for num in 0..max_point.x {
if count_here > count { let beam = Beam {
count = count_here; point: if is_vert { Point { x: num, y: num2 } } else { Point { x: num2, y: num } },
println!("New max: {} at {},{}", count, num, num2); vector
} };
let count_here = get_count(max_point, &rows, &columns, beam);
if count_here > count {
count = count_here;
println!("New max: {} at {},{}", count, num, num2);
}
}
count
})
)
}
let mut count = 0;
for thread in threads {
let count_here = thread.join().unwrap();
if count_here > count {
count = count_here;
} }
} }
println!("Max count: {}", count); println!("Max count: {}", count);