Created
March 19, 2025 17:37
-
-
Save nodlAndHodl/0734eaf9c870172d5782c4cb682063d5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread; | |
use std::sync::Arc; | |
use std::sync::atomic::AtomicI32; | |
use std::sync::atomic::Ordering; | |
fn main() { | |
let total = add(46, -4); | |
println!("total = {};", total) | |
} | |
fn add(n1: i32, n2: i32) -> i32 { | |
let sum = Arc::new(AtomicI32::new(n1)); | |
let (count, increment) = if n2 > 0 {(n2, 1)} else {(-n2, -1)}; | |
let mut handles = vec![]; | |
for _ in 0..count { | |
let inner_sum = Arc::clone(&sum); | |
handles.push( | |
thread::spawn(move ||{ | |
inner_sum.fetch_add(increment, Ordering::SeqCst); | |
}) | |
) | |
} | |
for handle in handles{ | |
handle.join().unwrap(); | |
} | |
sum.load(Ordering::SeqCst) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment