本文簡要介紹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 JoinHandle.join用法及代碼示例
- Rust JoinHandle.thread用法及代碼示例
- Rust UdpSocket.set_multicast_loop_v6用法及代碼示例
- Rust i64.overflowing_add_unsigned用法及代碼示例
- Rust Box.downcast用法及代碼示例
- Rust BTreeMap.last_key_value用法及代碼示例
- Rust str.make_ascii_uppercase用法及代碼示例
- Rust u128.checked_pow用法及代碼示例
- Rust usize.wrapping_mul用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust PanicInfo.payload用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust String.try_reserve用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust f32.exp用法及代碼示例
- Rust Result.unwrap_or_else用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust i128.log2用法及代碼示例
- Rust OsStr.to_ascii_uppercase用法及代碼示例
- Rust f32.hypot用法及代碼示例
- Rust RefCell.try_borrow_unguarded用法及代碼示例
- Rust i16.log10用法及代碼示例
- Rust LowerExp用法及代碼示例
- Rust HashSet.get_or_insert_with用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Struct std::thread::JoinHandle。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。