Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Last active December 31, 2024 19:01
Show Gist options
  • Save 0ex-d/9846e0680d3a0464f3e683c6fed835ed to your computer and use it in GitHub Desktop.
Save 0ex-d/9846e0680d3a0464f3e683c6fed835ed to your computer and use it in GitHub Desktop.
Cheapest blue collar worker you could hire 🎁 + without tokio runtime.
use std::thread;
use std::time::{Duration, Instant};
fn worker(id: isize) -> thread::JoinHandle<()> {
println!("starting worker {id}");
thread::spawn(move || {
thread::sleep(Duration::from_secs(10));
println!("worker {id} done");
})
}
fn main() {
let start_ts = Instant::now();
let range_of_souls = 1..100;
// now collect thread handles
let handles: Vec<_> = range_of_souls.map(|idx| worker(idx)).collect();
// Waiting 4 threads
for handle in handles {
handle.join().expect("Thread panicked");
}
println!("all workers done. took {:?}", start_ts.elapsed());
}
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Instant;
fn main() {
let start_ts = Instant::now();
let shared_counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for idx in 0..10 {
println!("starting counter {idx}");
let counter_clone = Arc::clone(&shared_counter);
let handle = thread::spawn(move || {
let mut counter = counter_clone.lock().unwrap();
*counter += 1;
println!("counter {idx} done");
});
handles.push(handle)
}
for handle in handles {
handle.join().expect("Thread panicked");
}
println!("all done. Final counter value: {:?} took {:?}",*shared_counter.lock().unwrap(), start_ts.elapsed());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment