#参考 #线程 #安全 #发送 #作用域 #通道

refcapsule

安全地向其他线程发送引用

1 个不稳定版本

0.1.0-beta12022年11月7日

#604并发

Apache-2.0

16KB
194

refcapsule

在 Rust 中安全地向其他线程发送引用

一种在通道中发送引用的作用域创建方法

示例

use std::thread;
use std::time::Duration;
use std::sync::mpsc::channel;
use refcapsule::{Capsule, with_encapsulated};

let (sender, receiver) = channel::<Capsule<u32>>();

// receiver of references

thread::spawn(move || {
    {
        let r = receiver.recv().unwrap();
        thread::sleep(Duration::from_millis(100));
        assert_eq!(*r, 4);
    }
    {
        let r = receiver.recv().unwrap();
        thread::sleep(Duration::from_millis(100));
        assert_eq!(*r, 12);
    }
});

let x: u32 = 4;
let s1 = sender.clone();
with_encapsulated(&x, move |x| s1.send(x).unwrap());

with_encapsulated(&12, move |cap| sender.send(cap).unwrap());

lib.rs:

此模块与作用域线程类似,但允许通过通道或其他机制将引用传递给其他线程。

它捕获零个或多个特定生命周期的“胶囊”内的引用,然后在所有该生命周期胶囊被丢弃之前不会返回控制权的环境中运行一个函数。

由于它会在“胶囊”被丢弃时阻塞等待,因此可以将胶囊安全地传递给其他线程(例如通过通道),在那里它们可以再次作为引用解引用。

示例

use std::thread;
use std::time::Duration;
use std::sync::mpsc::channel;
use refcapsule::{Capsule, with_encapsulated};

let (sender, receiver) = channel::<Capsule<u32>>();

// receiver of references

thread::spawn(move || {
    {
        let r = receiver.recv().unwrap();
        thread::sleep(Duration::from_millis(100));
        assert_eq!(*r, 4);
    }
    {
        let r = receiver.recv().unwrap();
        thread::sleep(Duration::from_millis(100));
        assert_eq!(*r, 12);
    }
});

let x: u32 = 4;
let s1 = sender.clone();
with_encapsulated(&x, move |x| s1.send(x).unwrap());

with_encapsulated(&12, move |cap| sender.send(cap).unwrap());

无法编译的内容

封装时修改原始变量

use refcapsule::with_encapsulated;

let mut x = 43;
with_encapsulated(&mut x, |y| {
    x = 4;
});

封装的生命周期短于封装作用域

use refcapsule::{with_encapsulated, encapsulate::gen};

with_encapsulated(gen(|s| {
    let x = 43;
    s.encapsulate(&x);
}), |x| {});

使用生成器函数封装引用时修改原始变量

use refcapsule::{with_encapsulated, encapsulate::gen};

let mut x = 43;
with_encapsulated(gen(|s| {
    s.encapsulate_mut(&mut x);
}), |y| {
    x = 4;
});

保存作用域以更长时间持续

use refcapsule::{with_encapsulated, encapsulate::gen};
with_encapsulated(gen(|s| s), |s| ());

无运行时依赖