RUST——线程创建

用spawn创建线程

在rust中创建线程是通过标准库中的thread::spawn函数来创建线程,spawn函数的参数是一个闭包,创建线程的示例代码如下:

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

fn main() {
    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));
    }
}

用join方法等等待线程结束

在上面的例子中,我们只是创建了线程,但是主线程并没有等待子线程结束执行。这样一来,当主线程结束的时候,不论子线程是否结束,都会结束执行。为了让主线程等待子线程结束执行,我们使用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语义的使用

如果我们需要在新创建的线程中使用主线程中的数据,我们需要使用rust中的move语义,来转移数据的所有权,以实现线程安全。

  1. 不使用move语义的示例代码
use std::thread;

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

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

    handle.join().unwrap();
}

在上面的示例代码中,我们在新创建的子线程中使用了在主线程中定义的向量v,如果我们编译上面的代码,我们会得到以下结果:

Compiling thread_move_demo v0.1.0 (E:\CLionProjects\thread_move_demo)
error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
 --> src\main.rs:6:32
  |
6 |     let handle = thread::spawn(|| {
  |                                ^^ may outlive borrowed value `v`
7 |         println!("Here is a vector: {:?}", v);
  |                                            - `v` is borrowed here
  |
note: function requires argument type to outlive `'static`
 --> src\main.rs:6:18
  |
6 |       let handle = thread::spawn(|| {
  |  __________________^
7 | |         println!("Here is a vector: {:?}", v);
8 | |     });
  | |______^
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
  |
6 |     let handle = thread::spawn(move || {
  |                                ++++

For more information about this error, try `rustc --explain E0373`.
error: could not compile `thread_move_demo` due to previous error

从上面编译的结果可以看出来,rust提示我们需要使用move把向量v的所有权转移到新创建的子线程上去,故而修改后的代码如下所示:

use std::thread;

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

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

    handle.join().unwrap();
}

代码执行的结果如下所示:

Here is a vector: [1, 2, 3]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值