1 个不稳定版本
0.1.0 | 2024年1月30日 |
---|
849 在 并发
17KB
111 行
此 crate 引入了专门的 ThreadLock
结构体。此结构体存储任意数据,但在运行时只允许从特定线程访问它;作为交换,ThreadLock
本身是 Send
和 Sync
。
这用途非常有限,但有时在某个结构体的一些部分必须进行多线程处理,而其他部分不能的情况下,它可能是有用的。通常,这些应该被拆分成不同的结构体(其中一个为 Sync
而另一个不是),但偶尔这可能是一个更简单的方法。
一个类似实际使用的(虚构的)示例
struct A; // A: Sync
struct B;
impl !Sync for B {}
pub struct AB {
a: A,
b: ThreadLock<B>
}
impl AB {
pub fn new() -> Self {
let (a, b): (A, B) = construct_ab();
Self { a, b: ThreadLock::new(b) }
}
pub fn foo(&self) { // any thread is allowed to call AB::foo
do_something_with_a(&self.a);
}
pub fn foo_and_bar(&self) {
let b = self.b.try_get().expect("foo_and_bar is only allowed on the same thread that AB was constructed");
do_something_with_a(&self.a);
do_something_with_b(b);
}
}
此示例的显著特点
- 我想能够在所有线程上做一些
AB
可以做的事情,所以我希望AB
是Sync
。 AB
可以做的事情中的一些(特别是foo_and_bar
)需要AB
拥有资源(特别是B
),这些资源不能在多个线程之间共享,以及多线程资源。A
和B
只能一起构建;这不太重要,但它可能会使得将AB
拆分成不同的结构体更困难或更不直观。