首页 > 其他 > 详细

Rust Lang Book Ch.16 Concurrency

时间:2020-10-27 23:06:04      阅读:31      评论:0      收藏:0      [点我收藏+]

使用线程来并行化任务一方面可以加快速度,避免因为IO等待耗费太久时间,另外一方面,也带来了资源竞争,死锁和潜在的难以复现的种种bug。不同的编程语言采取不同策略来生成管理调度线程,如果用户在编程语言中申请一个线程,就通过系统接口获取系统的一个线程,那么就称之为1:1模型。编程语言提供的线程被称为green thread,每M个green threads对应N个系统线程的模型就被称之为M:N模型。为了保证Rust在每个binary上附带的runtime code,即额外需要的用于运行的代码最少,Rust只提供了1:1线程模型。

thread::spawn

Rust使用thread::spawn来创建简单的线程JoinHandle,并且可以用JoinHandle::join()来等待所有的线程返回

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}

  

move使得线程能访问另一个线程中的数据

线程可以使用move来获得另一个线程中拥有的变量(captured variable)的ownership,当然,在move之后,这个变量就不能在原来的线程中使用了。

use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here‘s a vector: {:?}", v);
    });

    handle.join().unwrap();
}

  

如果尝试继续用,比如试着drop,就会报错:

use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here‘s a vector: {:?}", v);
    });

    drop(v); // oh no!
           ^ value used here after move
    handle.join().unwrap();
}

  

 

Rust Lang Book Ch.16 Concurrency

原文:https://www.cnblogs.com/xuesu/p/13887552.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!