我是Rust的新手,我想用併發來總結大量的數字。我發現這個代碼:如何總結使用Rust的併發性從1到1000000?
use std::thread;
use std::sync::{Arc, Mutex};
static NTHREAD: usize = 10;
fn main() {
let mut threads = Vec::new();
let x = 0;
// A thread-safe, sharable mutex object
let data = Arc::new(Mutex::new(x));
for i in 1..(NTHREAD+1) {
// Increment the count of the mutex
let mutex = data.clone();
threads.push(thread::spawn(move || {
// Lock the mutex
let n = mutex.lock();
match n {
Ok(mut n) => *n += i,
Err(str) => println!("{}", str)
}
}));
}
// Wait all threads ending
for thread in threads {
let _ = thread.join().unwrap();
}
assert_eq!(*data.lock().unwrap(), 55);
}
這工作時,線程是10,但是當線程大於20
我認爲它應該在任意數量的線程被罰款不起作用。
我誤解了什麼嗎?有沒有另外一種方法總結1到1000000的併發性?
爲了您的具體的例子,如果你有4個線程,只是總結'1..250k','250k..500k'等,每個線程然後總結線程函數的返回。你必須記住,每個並行計算案例都是獨一無二的,一切都取決於你的問題。 – Boiethios
「,但當線程大於20時不工作」當你有超過20個線程時會發生什麼?這些細節不值得省略。 –
我認爲OP說他不能在桌面電腦中產生1M線程。 – Boiethios