# 四.计算
use std::{
sync::{Arc, Mutex},
thread::spawn,
};
use rand::{thread_rng, Rng};
fn main() {
const COUNT: i32 = 100000000;
const NUM: i32 = 12;
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for k in 0..NUM {
let count = counter.clone();
let hander = spawn(move || {
for v in 0..COUNT {
let mut rand = thread_rng();
let x = rand.gen::<f32>();
let y = rand.gen::<f32>();
if x * x + y * y <= 1.0 {
let mut s = count.lock().unwrap();
*s += 1
}
}
});
handles.push(hander)
}
for v in handles {
v.join().unwrap()
}
let count = 4.0 * *counter.lock().unwrap() as f64;
println!("dddd {} dddd", count / (COUNT * NUM) as f64)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34