28个版本 (18个稳定版)

2.0.1 2024年6月3日
1.2.4 2024年3月14日
1.2.1 2023年11月13日
0.3.0 2023年7月12日

异步类别中排名第458

Download history 1/week @ 2024-05-17 81/week @ 2024-05-24 184/week @ 2024-05-31 31/week @ 2024-06-07 7/week @ 2024-06-14 9/week @ 2024-07-05 157/week @ 2024-07-26 17/week @ 2024-08-02

每月下载量174

MIT/Apache

300KB
6K SLoC

interthread

该crate提供的actor宏自动化实现给定结构体或枚举的Actor模型。它处理消息路由和同步的复杂性,使开发者能够快速原型化其应用程序的核心功能。这种快速草图能力在探索不同的设计选项、实验并发模型或实现概念验证系统时尤其有用。而且,当程序的重要性在于其工作结果而不是其执行时,这一点更为明显。

示例

文件名:Cargo.toml

[dependencies]
interthread = "2.0.1"
oneshot     = "0.1.6" 

文件名:main.rs


pub struct MyActor {
    value: i8,
}

#[interthread::actor(show)] // <-  this is it 
impl MyActor {
    
    /// This is my comment
    pub fn new( v: i8 ) -> Self {
       Self { value: v } 
    }
    pub fn increment(&mut self) {
        self.value += 1;
    }
    pub fn add_number(&mut self, num: i8) -> i8 {
        self.value += num;
        self.value
    }
    pub fn get_value(&self) -> i8 {
        self.value
    }
}

// try hovering over model parts to see
// generated code as a comment
fn main() {

    let actor = MyActorLive::new(5);

    let mut actor_a = actor.clone();
    let mut actor_b = actor.clone();

    let handle_a = std::thread::spawn( move || { 
    actor_a.increment();
    });

    let handle_b = std::thread::spawn( move || {
    actor_b.add_number(5)
    });

    let _  = handle_a.join();
    let hb = handle_b.join().unwrap();

    // we never know which thread will
    // be first to call the actor so
    // hb = 10 or 11
    assert!(hb >= 10);

    assert_eq!(actor.get_value(), 11);
}

此外,当与file选项结合使用时,edit选项便于将生成的代码的部分写入文件。要使用代码替换宏,在宏中使用edit(file)

相同的示例可以在以下环境中运行:

唯一的不同之处在于,方法将被标记为async,需要使用await进行异步执行。

依赖

~1.6–2.3MB
~47K SLoC