1use std::thread;2
3fn is_prime(n: i32) -> bool {4 let mut result = true;5 for k in 2..(n as f32).powf(0.5) as i32 + 1 {6 if n % k == 0 {7 result = false;8 break;9 }10 }11 result12}13
14fn count_primes(start: i32, end: i32) -> i32 {15 let mut count = 0;36 collapsed lines
16 for k in start..end {17 if is_prime(k) {18 count += 1;19 }20 }21 count22}23
24fn main() {25 const THREAD_COUNT: usize = 15; // 设置线程数量26
27 let n = 1e8 as i32;28 let chunk_size = n / THREAD_COUNT as i32;29
30 let mut handles = vec![];31
32 for i in 0..THREAD_COUNT {33 let start = i as i32 * chunk_size + 2;34 let end = if i == THREAD_COUNT - 1 {35 n36 } else {37 (i + 1) as i32 * chunk_size + 238 };39
40 let handle = thread::spawn(move || count_primes(start, end));41 handles.push(handle);42 }43
44 let mut total_count = 0;45
46 for handle in handles {47 total_count += handle.join().unwrap();48 }49
50 println!("{}", total_count);51}
Article title:thread-spawn
Article author:Julyfun
Release time:Mar 6, 2024
Original link:https://how-to.fun/blog/langs/rust/examples/thread-spawn
Copyright 2025
Sitemap