Skip to content

Instantly share code, notes, and snippets.

@nodlAndHodl
Created March 19, 2025 18:17
Show Gist options
  • Save nodlAndHodl/06baa9b3db7ea18fc8fffd68331d1a35 to your computer and use it in GitHub Desktop.
Save nodlAndHodl/06baa9b3db7ea18fc8fffd68331d1a35 to your computer and use it in GitHub Desktop.
use std::thread;
use std::sync::mpsc;
fn main() {
let total = add(46, -4);
println!("total = {};", total)
}
fn add(n1: i32, n2: i32) -> i32 {
let mut sum = n1;
let (count, increment) = if n2 > 0 {(n2, 1)} else {(-n2, -1)};
let mut handles = vec![];
let (tx, rx) = mpsc::channel();
for _ in 0..count {
let tx_for_thread = tx.clone();
handles.push(
thread::spawn(move || {
tx_for_thread.send(increment).unwrap();
})
);
}
for handle in handles { handle.join().unwrap(); }
for _ in 0..count{
sum += rx.recv().unwrap();
}
sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment