Code RoomCounter reads low
MediumPrep Room Coding #2208

Counter reads low

Code reviewConcurrencyMid–Senior~28 min

Review this Rust code that aggregates results across threads (assume it's been forced to compile with unsafe interior mutability).

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.

0:00 of about 28 min
Mark a line and say what kind of problem it is.0 findings
1use std::sync::Arc;
2use std::cell::UnsafeCell;
3use std::thread;
4 
5struct Counter { v: UnsafeCell<u64> }
6unsafe impl Sync for Counter {}
7 
8fn main() {
9 let c = Arc::new(Counter { v: UnsafeCell::new(0) });
10 let mut hs = vec![];
11 for _ in 0..8 {
12 let c = Arc::clone(&c);
13 hs.push(thread::spawn(move || {
14 for _ in 0..100_000 {
15 unsafe { *c.v.get() += 1; }
16 }
17 }));
18 }
19 for h in hs { h.join().unwrap(); }
20 println!("{}", unsafe { *c.v.get() });
21}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.