Module ractor::pg

source ·
Expand description

Process groups (PG) are named groups of actors with a friendly name which can be used for retrieval of the process groups. Then within the group, either a random actor (for dispatch) can be selected or the whole group (broadcast), or a subset (partial-broadcast) can have a message sent to them. Common operations are to (a) upcast the group members to a strong-type’d actor then dispatch a message with crate::call or crate::cast.

Process groups can also be monitored for changes with calling monitor to subscribe to changes and demonitor to unsubscribe. Subscribers will receive process group change notifications via a SupervisionEvent called on the supervision port of the crate::Actor

Inspired from Erlang’s pg module

§Examples

use ractor::pg;
use ractor::{Actor, ActorProcessingErr, ActorRef};

struct ExampleActor;

#[cfg_attr(feature = "async-trait", ractor::async_trait)]
impl Actor for ExampleActor {
    type Msg = ();
    type State = ();
    type Arguments = ();

    async fn pre_start(
        &self,
        _myself: ActorRef<Self::Msg>,
        _args: Self::Arguments,
    ) -> Result<Self::State, ActorProcessingErr> {
        println!("Starting");
        Ok(())
    }
}

#[tokio::main]
async fn main() {
    let (actor, handle) = Actor::spawn(None, ExampleActor, ())
        .await
        .expect("Failed to startup dummy actor");
    let group = "the_group".to_string();

    // Join the actor to a group. This is also commonly done in `pre_start` or `post_start`
    // of the actor itself without having to do it externally by some coordinator
    pg::join(group.clone(), vec![actor.get_cell()]);
    // Retrieve the pg group membership
    let members = pg::get_members(&group);
    // Send a message to the up-casted actor
    let the_actor: ActorRef<()> = members.get(0).unwrap().clone().into();
    ractor::cast!(the_actor, ()).expect("Failed to send message");

    // wait for actor exit
    actor.stop(None);
    handle.await.unwrap();

    // The actor will automatically be removed from the group upon shutdown.
    let members = pg::get_members(&group);
    assert_eq!(members.len(), 0);
}

Structs§

  • Represents the combination of a ScopeName and a GroupName that uniquely identifies a specific group in a specific scope

Enums§

Constants§

Functions§