Rust:Parallelism through simple threads

内容纲要

Parallelism through simple threads

Every year, parallelism and concurrency become more important as processors tend to have more and more physical cores. In most languages, writing parallel code is tricky. Very tricky. Not so in Rust, as it has been designed around the principle of fearless concurrency since the beginning.

[dependencies]
rand = "0.7.0"

use mod:

use rand::Rng;
use std::thread;

This is the function that will be executed in the threads.

要在线程中执行的任务/函数:

fn sum_bucket(range: &[i32]) -> i32 {
    let mut sum = 0;
    for num in range {
        sum += *num;
    }
    sum
}

创建 100 个数字,每个线程执行其中 10 数字的和运算。

fn main() {
    // 创建二维数组
    let mut array: [[i32; 10]; 10] = Default::default();

    // 随机数
    let mut rng = rand::thread_rng();

    // 给数组赋值
    for item in array.iter_mut() {
        for itemChild in item {
            *itemChild = rng.gen_range(0, 10);
        }
    }

    // 存储线程结果(句柄)
    let mut threads = Vec::new();
    let mut count = 0;

    // 创建 10 个线程,每个线程计算 10 个数字
    while count < array.len() {
        let thread = thread::Builder::new()
            .name(format!("thread {}", count))
            .spawn(move || sum_bucket(&array[count]))
            .expect("error");

        threads.push(thread);
        count += 1;
    }

    let allSum = {
        let mut tmp: i32 = 0;
        for item in threads {
            tmp += item.join().expect("线程执行错误");
        }
        tmp
    };

    println!("{}", allSum);
}
点赞

发表评论

邮箱地址不会被公开。 必填项已用*标注

You must enable javascript to see captcha here!