#actor #async #thread #actor-model

macro interthread

Auto implementation of the Actor Model

24 releases (14 stable)

1.2.2 Feb 20, 2024
1.2.1 Nov 13, 2023
1.1.7 Sep 21, 2023
1.1.3 Aug 30, 2023
0.1.8 Jun 28, 2023

#382 in Asynchronous

Download history 23/week @ 2023-11-06 29/week @ 2023-11-13 75/week @ 2023-11-20 78/week @ 2023-11-27 4/week @ 2023-12-04 26/week @ 2023-12-11 52/week @ 2023-12-25 23/week @ 2024-01-01 53/week @ 2024-01-29 3/week @ 2024-02-05 111/week @ 2024-02-12 805/week @ 2024-02-19

972 downloads per month

MIT/Apache

280KB
5.5K SLoC

interthread

The actor macro provided by this crate automates the implementation of an Actor Model for a given struct or enum. It handles the intricacies of message routing and synchronization, empowering developers to swiftly prototype the core functionality of their applications. This fast sketching capability is particularly useful when exploring different design options, experimenting with concurrency models, or implementing proof-of-concept systems. Not to mention, the cases where the importance of the program lies in the result of its work rather than its execution.

Examples

Filename: Cargo.toml

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

Filename: main.rs


pub struct MyActor {
    value: i8,
}

#[interthread::actor] // <-  this is it 
impl MyActor {

    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
    }
}

// uncomment to see the generated code
//#[interthread::example(path="src/main.rs")] 
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);
}

Be sure to explore the example macro provided by this crate, as it proves to be an invaluable tool for debugging and visualizing the code generated by the actor macro. Additionally, the edit option, when combined with the file option, facilitates writing the requested part of the generated code to the file. To substitute the macro with code on file, utilize edit(file) within the macro.

The same example can be run in

with the only difference being that the methods will be marked as async and need to be awaited for asynchronous execution.

Dependencies

~3MB
~63K SLoC