Struct std::thread::JoinHandle1.0.0[][src]

pub struct JoinHandle<T>(_);
Expand description

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

JoinHandle 被丢弃时,它会分离关联的线程,这意味着不再有线程的任何句柄,也无法在其上使用 join

由于平台的限制,无法使用 Clone 此句柄:加入线程的能力是唯一拥有的权限。

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

Examples

thread::spawn 创建:

use std::thread;

let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
    // 这里一些工作
});
Run

thread::Builder::spawn 创建:

use std::thread;

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

let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
    // 这里一些工作
}).unwrap();
Run

一个线程被分离并且比产生它的线程生命周期更长:

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

let original_thread = thread::spawn(|| {
    let _detached_thread = thread::spawn(|| {
        // 在这里我们睡觉以确保第一个线程在此之前返回。
        thread::sleep(Duration::from_millis(10));
        // 即使 JoinHandle 被丢弃,也将调用它。
        println!("♫ Still alive ♫");
    });
});

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

// 我们确保在主线程返回之前,新线程有时间运行。

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

Implementations

提取底层线程的句柄。

Examples
use std::thread;

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

let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
    // 这里一些工作
}).unwrap();

let thread = join_handle.thread();
println!("thread id: {:?}", thread.id());
Run

等待关联的线程完成。

如果关联的线程已经完成,这个函数将立即返回。

原子内存排序 而言,关联线程的完成与此函数返回同步。 换句话说,该线程 之前发生过 执行的所有操作都是在 join 返回之后发生的所有操作。

如果关联的线程 panics,则返回 Err,并返回给 panic! 的参数。

Panics

如果某个线程尝试加入自身,则该函数在某些平台上可能为 panic,否则可能会在加入线程时产生死锁。

Examples
use std::thread;

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

let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
    // 这里一些工作
}).unwrap();
join_handle.join().expect("Couldn't join on the associated thread");
Run
🔬 This is a nightly-only experimental API. (thread_is_running #90470)

检查关联的线程是否仍在运行其对应的 main 函数。

这可能会在线程的 main 函数返回后的一小段时间内返回 false,但在线程本身停止运行之前。

Trait Implementations

🔬 This is a nightly-only experimental API. (io_safety #87074)

借用句柄。 Read more

提取原始句柄,无需任何所有权。

使用给定的格式化程序格式化该值。 Read more

执行转换。

消耗此对象,返回原始底层句柄。 Read more

提取原始 pthread_t 而不拥有所有权

消耗线程,返回原始 pthread_t Read more

Auto Trait Implementations

Blanket Implementations

获取 selfTypeIdRead more

从拥有的值中一成不变地借用。 Read more

从拥有的值中借用。 Read more

执行转换。

执行转换。

发生转换错误时返回的类型。

执行转换。

发生转换错误时返回的类型。

执行转换。