面向云技术架构 - 痴者工良

  • 首页
  • 工良写的电子书
    • kubernetes 教程
    • 从 C# 入门 Kafka
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 本站文章导航
  • 隐私政策
愿有人陪你颠沛流离
遇到能让你付出的事物或者人,都是一种运气。
能遇到,就该珍惜。或许你们最终没能在一起,但你会切实地感受到力量。
正因为这样,那段相遇才变得有价值,才没有辜负这世间的每一段相遇。
  1. 首页
  2. 编程语言
  3. rust
  4. 正文

Rust:Parallelism through simple threads

2020年11月23日 1356点热度 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.

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

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);
}
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: parallelism rust simple threads through
最后更新:2021年2月21日

痴者工良

高级程序员劝退师

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

文章目录
  • Parallelism through simple threads

COPYRIGHT © 2022 whuanle.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备18051778号

粤公网安备 44030902003257号