Last active
December 31, 2024 19:01
-
-
Save 0ex-d/9846e0680d3a0464f3e683c6fed835ed to your computer and use it in GitHub Desktop.
Cheapest blue collar worker you could hire π + without tokio runtime.
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::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()); | |
} |
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::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