Struct std::thread::JoinHandle 1.0.0[−][src]
pub struct JoinHandle<T>(_);
Expand description
拥有加入线程的权限 (在线程终止时阻止)。
当 JoinHandle
被丢弃时,它会分离关联的线程,这意味着不再有线程的任何句柄,也无法在其上使用 join
。
由于平台的限制,无法使用 Clone
此句柄:加入线程的能力是唯一拥有的权限。
该 struct
由 thread::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));
RunImplementations
等待关联的线程完成。
如果关联的线程已经完成,这个函数将立即返回。
就 原子内存排序 而言,关联线程的完成与此函数返回同步。
换句话说,该线程 之前发生过 执行的所有操作都是在 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检查关联的线程是否仍在运行其对应的 main
函数。
这可能会在线程的 main
函数返回后的一小段时间内返回 false
,但在线程本身停止运行之前。
Trait Implementations
提取原始句柄,无需任何所有权。
执行转换。
消耗此对象,返回原始底层句柄。 Read more
提取原始 pthread_t 而不拥有所有权
消耗线程,返回原始 pthread_t Read more