• 【早晨读书会】深入理解rust并发编程


    第一章 线程

    线程

    线程是调度的最小单位

    同一进程中的多条线程将共享该进程中的全部系统资源,如虚拟地址空间,文件描述符和信号处理等等。但同一进程中的多个线程有各自的调用栈(call stack),自己的寄存器上下文(register context),自己的线程本
    地存储(thread-local storage)。

    SmallTalk、Ruby、Lua、Python 等,还会有协程(英语:coroutine)更小的调度单位。协程非常类似于线程。但是协程是协作式多任务的,而线程典型是抢占式多任务的。这意味着协程提供并发性而非并行性。

    Rust 实现并发的基本单位是线程

    Rust 标准库std::thread crate 提供了线程相关的函数。正如上面所说,一个 Rust 程序执行的会启动一个进程,这个进程会包含一个或者多个线程,Rust 中的线程是纯操作的系统的线程,拥有自己的栈和状态。线程之间的通讯可以通过 channel,就像 Go 语言中的 channel 的那样,也可以通过一些同步原语。

    Thread builder
    通过 Builder 你可以对线程的初始状态进行更多的控制,比如设置线程的名称、栈大大小等等。

    pub fn start_one_thread_by_builder() {
     let builder = thread::Builder::new()
     	.name("foo".into()) // set thread name
     	.stack_size(32 * 1024); // set stack size
    
     let handler = builder
     	.spawn(|| {
    	 println!("Hello from a thread!");
    	 })
    	.unwrap();
    
    	 handler.join().unwrap();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    你可以通过 available_parallelism 获取当前的并发数
    affinity (不支持 MacOS) crate 可以提供当前的 CPU 核数
    更多的场景下,我们使用 num_cpus 获取 CPU 的核数(逻辑核)

    (Rust 生态圈就是这样,有很多功能相同或者类似的 crate, 你可能需要花费时间进行评估和比较, 不像 Go 生态圈,优选标准库的包,如果没有,生态圈中一般会有一个或者几个高标准的大家公认的库可以使用。相对而言,Rust 生态圈就比较分裂, 这一点在选择异步运行时或者网络库的时候感受相当明显。)

    sleep and park

    有时候我们我们需要将当前的业务暂停一段时间,可能是某些条件不满足,比如实现spinlock, 或者是想定时的执行某些业务,如 cron 类的程序,这个时候我们可以调用thread::sleep 函数.
    它至少保证当前线程 sleep 指定的时间。因为它会阻塞当前的线程,所以不要在异步的代码中调用它。如果时间设置为 0, 不同的平台处理是不一样的,Unix 类的平台会立即返回,不会调用 nanosleep 系统调用,而 Windows 平台总是会调用底层的 Sleep系统调用。如果你只是想让渡出时间片,你不用设置时间为 0,而是调用 yield_now 函数即可。
    如果在休眠时间不确定的情况下,我们想让某个线程休眠,将来在某个事件发生之后,我们再主动的唤醒它,那么就可以使用我们前面介绍的 park 和 unpark 方法了。
    一个线程只有一个令牌用来负责park和unpark

    scoped thread

    它可以借用 scope 外部的非 ‘static’ 数据。使用thread::scope 函数提供的 Scope 的参数,可以创建 (spawn) scoped thread。创建出来的 scoped thread 如果没有手工调用 join , 在这个函数返回前会自动 join 。

    1 pub fn wrong_start_threads_without_scoped() {
    2 let mut a = vec![1, 2, 3];
    3 let mut x = 0;
    4
    5 thread::spawn(move || {
    6 println!("hello from the first scoped thread");
    7 dbg!(&a);
    8 });
    9 thread::spawn(move || {
    10 println!("hello from the second scoped thread");
    11 x += a[0] + a[2];
    12 });
    13 println!("hello from the main thread");
    14
    15 // After the scope, we can modify and access our variables again:
    16 a.push(4);
    17 assert_eq!(x, a.len());
    18 }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    上述代码无法编译,因为a被放入了许多个线程中。要知道所有权一旦交出去就无法再交给其他人了,东西已经送出去了。
    如果你需要多次给到其他线程就需要进行scope thread

    1 pub fn start_scoped_threads() {
    2 let mut a = vec![1, 2, 3];
    3 let mut x = 0;
    5 thread::scope(|s| {
    6		 s.spawn(|| {
    7	 	println!("hello from the first scoped thread");
    8 		dbg!(&a);
    9		 });
    10 		s.spawn(|| {
    11	 	println!("hello from the second scoped thread");
    12 		x += a[0] + a[2];
    13		 });
    14 		println!("hello from the main thread");
    15 });
    16
    17 // After the scope, we can modify and access our variables again:
    18 		a.push(4);
    19 		assert_eq!(x, a.len());
    20 }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    因为我们对 a 只是读,对 x 只有单线程的写,所以不用考虑并发问题。thread::scope 返回后,两个线程已经执行完毕,所以外部的线程又可以访问变量了。
    如果你希望启动一个线程但是又不希望交出数据的所有权,那么加上一个限制我单线程的去处理这个数据以避免并发的问题就可以实现启动线程却不交出所有权。

  • 相关阅读:
    Python 合并两张图片
    Java web速成之jsp
    Spring IoC容器生命周期内容梳理
    高级_09.性能分析工具的使用
    物联网python开发实践
    SpringCloud之Sentinel概述和安装及简单整合
    Simulink代码生成: 查表模块及其代码
    网络运维Day04-补充
    字符串查询--Python
    Go 程序太大了,能要个延迟初始化不?
  • 原文地址:https://blog.csdn.net/qq_54384621/article/details/138144538