美文网首页RUST编程
Rust 编程视频教程(进阶)——016_2 创建线程与等待线程

Rust 编程视频教程(进阶)——016_2 创建线程与等待线程

作者: 令狐壹冲 | 来源:发表于2020-02-12 10:19 被阅读0次

视频地址

头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rust

讲解内容

1、创建线程
(1)方法:调用thread::spawn即可

(2)例子:

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));
    }
}

2、等待线程结束
上面的例子中,在主线程结束之前并不能保证所有子线程都结束了(主线程提前结束,就不能保证这些子线程都执行了),因此通过以下方法等待子线程结束。

(1)方法:join

(2)例子1:

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

(3)例子2:

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));
        }
    });

    handle.join().unwrap();

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

相关文章

网友评论

    本文标题:Rust 编程视频教程(进阶)——016_2 创建线程与等待线程

    本文链接:https://www.haomeiwen.com/subject/ocuqfhtx.html