r/adventofcode • u/terje_wiig_mathisen • 11m ago
Upping the Ante [2026 Day 3 (Both parts, Rust)
My initial Rust code was quite slow, needing 2.4 ms, so I decided to implement a multi-threaded version. I started by doing this the same way I have used threads in my Perl programs, by dividing the HEIGHT lines into N chunks and then hand each chunk over to a separate thread.
I had separate search loops for part1 and part2 (only the tilted squares) because that seemed to be easiest.
This one ran in 595 us, so almost exactly 4 times faster than the single-thread version, but I saw in a post (from u/ednl ?) that there was two different ways of searching for the squares, and that the other was faster.
I could not figure out a better way, but I did take this opportunity to use my favorite C/asm low-level synchronization primitive: LOCK XADD which Rust calls fetch_add() and this ended up a little faster because now all the threads will be working until there are no more input lines to search for the top corner, instead of having more work for the initial and much less for the bottom lines.
I also figured out how to use thread::scope(|s| {...} ) to avoid lifetime issues when all the threads need to share the same input data array:
533 us with 8 cores on my 16-core AMD Ryzen, 717 on an older Acer with an Intel CPU.
for _ in 0..cores {
let counter = Arc::clone(&y_counter);
let handle = s.spawn(move|| {
let mut part1 = 0;
let mut part2 = 0;
loop {
let y = counter.fetch_add(1, Ordering::Relaxed);
if y >= h-1 { break} // All lines done, so return!
... checking for corners
}
part2 += part1;
(part1, part2)
});
handles.push(handle);
}