Rust: Parallelism through Simple Threads

2020年11月23日 56点热度 0人点赞 0条评论
内容目录

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.

The task/function to be executed in the threads:

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

Create 100 numbers, with each thread computing the sum of 10 numbers.

fn main() {
    // Create a two-dimensional array
    let mut array: [[i32; 10]; 10] = Default::default();
// Random number generator
let mut rng = rand::thread_rng();

// Assign values to the array
for item in array.iter_mut() {
    for itemChild in item {
        *itemChild = rng.gen_range(0, 10);
    }
}

// Store thread results (handles)
let mut threads = Vec::new();
let mut count = 0;

// Create 10 threads, each calculating the sum of 10 numbers
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("Thread execution error");
    }
    tmp
};

println!("{}", allSum);

}

痴者工良

高级程序员劝退师

文章评论