当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust JoinHandle用法及代码示例


本文简要介绍rust语言中 Struct std::thread::JoinHandle 的用法。

用法

pub struct JoinHandle<T>(_);

加入线程的拥有权限(在其终止时阻塞)。

A JoinHandle 分离关联的线程被删除时,这意味着不再有任何线程句柄,也没有办法join在上面。

由于平台限制,无法 Clone 这个句柄:加入线程的能力是 uniquely-owned 权限。

struct thread::spawn 函数和 thread::Builder::spawn 方法创建。

例子

thread::spawn 创建:

use std::thread;

let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
    // some work here
});

thread::Builder::spawn 创建:

use std::thread;

let builder = thread::Builder::new();

let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
    // some work here
}).unwrap();

一个线程被分离并超过了产生它的线程:

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

let original_thread = thread::spawn(|| {
    let _detached_thread = thread::spawn(|| {
        // Here we sleep to make sure that the first thread returns before.
        thread::sleep(Duration::from_millis(10));
        // This will be called, even though the JoinHandle is dropped.
        println!("♫ Still alive ♫");
    });
});

original_thread.join().expect("The thread being joined has panicked");
println!("Original thread is joined.");

// We make sure that the new thread has time to run, before the main
// thread returns.

thread::sleep(Duration::from_millis(1000));

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Struct std::thread::JoinHandle。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。