#send-sync #sync #thread #environments #original #multi-threaded #don't

threadalone

使任何值都满足 Send + Sync,但仅在原始线程上可用。不要在多线程环境中使用!

1 个不稳定版本

0.2.1 2024年1月22日
0.2.0 2023年3月11日
0.1.0 2023年3月11日

并发 中排名 #286

每月下载量 42

MIT/Apache

11KB
66

ThreadAlone<T>

这是 dtolnay 的 threadbound crate 的分支,它允许在非 Copy 类型上实现 Send

原始 crate 不允许这样做的原因是,如果从创建它的线程之外的其他线程删除了 ThreadBound 对象,则无法以任何方式处理它。相反,此 crate 在这种情况下将 中止:因此,在多线程环境中使用此 crate 时请务必谨慎。


ThreadBound<T>

github crates.io docs.rs build status

ThreadBound 是一个包装器,将一个值绑定到其原始线程。包装器可以成为 SyncSend,但只有构建 ThreadBound 的原始线程可以检索底层值。

[dependencies]
threadbound = "0.1"

版本要求:rustc 1.31+


示例

extern crate threadbound;

use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
use threadbound::ThreadBound;

// Neither Send nor Sync. Maybe the index points into a
// thread-local interner.
#[derive(Copy, Clone)]
struct Span {
    index: u32,
    marker: PhantomData<Rc<()>>,
}

// Error types are always supposed to be Send and Sync.
// We can use ThreadBound to make it so.
struct Error {
    span: ThreadBound<Span>,
    message: String,
}

fn main() {
    let err = Error {
        span: ThreadBound::new(Span {
            index: 99,
            marker: PhantomData,
        }),
        message: "fearless concurrency".to_owned(),
    };

    // Original thread can see the contents.
    assert_eq!(err.span.get_ref().unwrap().index, 99);

    let err = Arc::new(err);
    let err2 = err.clone();
    std::thread::spawn(move || {
        // Other threads cannot get access. Maybe they use
        // a default value or a different codepath.
        assert!(err2.span.get_ref().is_none());
    });

    // Original thread can still see the contents.
    assert_eq!(err.span.get_ref().unwrap().index, 99);
}

许可

根据您的选择,在 Apache 许可证,版本 2.0MIT 许可证 下许可。
除非您明确说明,否则您提交给此 crate 的任何贡献,根据 Apache-2.0 许可证定义,应按上述方式双重许可,不附加任何额外条款或条件。

依赖项

~315–770KB
~17K SLoC