I am experimenting with multithreading in Rust. I have created a toy example based on the Sieve of Eratosthenes for finding primes. Each worker thread is given a list of primes to check as divisors for the new candidate.
for chunk in &primes {
let tx2 = mpsc::Sender::clone(&tx);
let p2 = Arc::clone(chunk);
thread::spawn(move || {
let result = divisible_by_any(i, &p2.lock().unwrap());
tx2.send(result).unwrap();
});
}
let mut any = false;
for _i in 0..primes.len() {
let result = rx.recv().unwrap();
if result { any = true }
}
One possible optimization is to allow the ringleader process to "interrupt" the worker threads as soon as any of the threads finds a divisor. I am imagining that the worker threads (divisible_by_any
) would not be killed, but would check for some kind of semaphore that would indicate if the "interruption" has been requested so it can stop scanning for divisors.
What is the Rust idiom for raising a semaphore that can be noticed/sampled by multiple CPU-bound worker threads?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…