Struct std::thread::Thread1.0.0[−][src]

pub struct Thread { /* fields omitted */ }
Expand description

线程的句柄。

线程通过 Thread 类型表示,您可以通过以下两种方式之一来获取:

thread::current 函数甚至可用于不是由该模块的 API 生成的线程。

通常不需要自己创建 Thread 结构体,而应使用 spawn 之类的函数来创建新线程,有关更多详细信息,请参见 Builder 和 spawn 的文档。

Implementations

通过原子方式使句柄的 token 可用 (如果尚不可用)。

每个线程都通过 park 函数和 unpark() 方法提供了一些基本的阻塞支持。 这些可用作自旋锁的 CPU 效率更高的实现。

有关更多详细信息,请参见 park 文档。

Examples

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

let parked_thread = thread::Builder::new()
    .spawn(|| {
        println!("Parking thread");
        thread::park();
        println!("Thread unparked");
    })
    .unwrap();

// 花费一些时间来生成线程。
thread::sleep(Duration::from_millis(10));

println!("Unpark the thread");
parked_thread.thread().unpark();

parked_thread.join().unwrap();
Run

获取线程的唯一标识符。

Examples

use std::thread;

let other_thread = thread::spawn(|| {
    thread::current().id()
});

let other_thread_id = other_thread.join().unwrap();
assert!(thread::current().id() != other_thread_id);
Run

获取线程的名称。

有关命名线程的更多信息,请参见 模块级文档。

Examples

默认情况下,线程未指定名称:

use std::thread;

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

let handler = builder.spawn(|| {
    assert!(thread::current().name().is_none());
}).unwrap();

handler.join().unwrap();
Run

具有指定名称的线程:

use std::thread;

let builder = thread::Builder::new()
    .name("foo".into());

let handler = builder.spawn(|| {
    assert_eq!(thread::current().name(), Some("foo"))
}).unwrap();

handler.join().unwrap();
Run

Trait Implementations

返回值的副本。 Read more

从 source 执行复制分配。 Read more

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

Auto Trait Implementations

Blanket Implementations

获取 self 的 TypeId。 Read more

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

从拥有的值中借用。 Read more

执行转换。

执行转换。

获得所有权后的结果类型。

通常通过克隆从借用数据中创建拥有的数据。 Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into #41263)

recently added

使用借来的数据来替换拥有的数据,通常是通过克隆。 Read more

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

执行转换。

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

执行转换。