我想在多個線程中改變一個可變的變量。我知道這不是線程安全的,但我想知道Rust編譯器將如何處理它。所以我用了一系列的map
功能產卵子線程:在多個線程中改變一個共享的可變變量
use std::thread;
fn break_law(value: &mut i32) {
*value += 20;
}
fn main() {
let mut x = 10;
let handles = (0..10).map(|| {
thread::spawn(move || {
break_law(&mut x);
println!("{:?}", x);
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
但我得到一個錯誤:
break_law1.rs:10:24: 15:4 error: type mismatch: the type `[[email protected]_law1.rs
:10:28: 15:3 x:_]` implements the trait `core::ops::FnMut<()>`, but the trait `c
ore::ops::FnMut<(_,)>` is required (expected tuple, found()) [E0281]
break_law1.rs:10 let handles = (0..10).map(|| {
break_law1.rs:11 thread::spawn(move || {
break_law1.rs:12 break_law(&mut x);
break_law1.rs:13 println!("{:?}", x);
break_law1.rs:14 })
break_law1.rs:15 }).collect();
break_law1.rs:10:24: 15:4 help: run `rustc --explain E0281` to see a detailed ex
planation
break_law1.rs:10:24: 15:4 error: type mismatch: the type `[[email protected]_law1.rs
:10:28: 15:3 x:_]` implements the trait `core::ops::FnOnce<()>`, but the trait `
core::ops::FnOnce<(_,)>` is required (expected tuple, found()) [E0281]
break_law1.rs:10 let handles = (0..10).map(|| {
break_law1.rs:11 thread::spawn(move || {
break_law1.rs:12 break_law(&mut x);
break_law1.rs:13 println!("{:?}", x);
break_law1.rs:14 })
break_law1.rs:15 }).collect();
break_law1.rs:10:24: 15:4 help: run `rustc --explain E0281` to see a detailed ex
planation
break_law1.rs:15:5: 15:14 error: type mismatch: the type `[[email protected]_law1.rs
:10:28: 15:3 x:_]` implements the trait `core::ops::FnMut<()>`, but the trait `c
ore::ops::FnMut<(_,)>` is required (expected tuple, found()) [E0281]
break_law1.rs:15 }).collect();
^~~~~~~~~
break_law1.rs:15:5: 15:14 help: run `rustc --explain E0281` to see a detailed ex
planation
break_law1.rs:18:6: 18:14 error: the type of this value must be known in this co
ntext
break_law1.rs:18 h.join().unwrap();
^~~~~~~~
break_law1.rs:17:2: 19:3 note: in this expansion of for loop expansion
error: aborting due to 4 previous errors
根據上述信息,我得到這個範圍內的map
函數的定義是這樣的:
// Creates a new iterator that will apply the specified function to each
// element returned by the first, yielding the mapped element instead.
fn map<B, F>(self, f: F) -> Map<Self, F>
where F: FnMut(Self::Item) -> B
這看起來很奇怪,但我該如何糾正?爲什麼?
它確實work.Thanks。這個函數簽名與C++完全不同。順便說一句,就像@swizard所說的那樣,每個線程都會收到一個變量x的副本,所以外部作用域中的x不會發生變異。 –