Skip to content

Actor Model

An actor is some code (a process, thread, or function) that you're going to pass a message to.

The core idea is:

  • You send the actor some instructions
  • It returns some information back to you by running the computation in a background process

  • Actors are background tasks that uses message passing to communicate with the rest of the program
  • When are they useful? IO resources that you want shared access to (websocket or database connection)
  • Actors are better than Arc<Mutex<T>> because
    • They initiate operations without outside influence
    • Operations can continue in the background

Recipe

rust
struct MyActor {
	receiver: mpsc::Receiver<ActorMessage>,
	connection: TcpStream,
}

/// The important part to understand here is that we pass ALL of the
/// information that the actor needs to call the controller code AND
/// a oneshot channel to relay the result back to where is was called
/// from
enum ActorMessage {
	SendMessage {
		message: String,
		respond_to: oneshot::Sender<u32> // This is the key
	}
}

impl MyActor {
		async fn handle_message(&mut self, msg: ActorMessage) -> io::Result<()> {
			
		}
}
struct MyActor {
	receiver: mpsc::Receiver<ActorMessage>,
	connection: TcpStream,
}

/// The important part to understand here is that we pass ALL of the
/// information that the actor needs to call the controller code AND
/// a oneshot channel to relay the result back to where is was called
/// from
enum ActorMessage {
	SendMessage {
		message: String,
		respond_to: oneshot::Sender<u32> // This is the key
	}
}

impl MyActor {
		async fn handle_message(&mut self, msg: ActorMessage) -> io::Result<()> {
			
		}
}
  • One-shot channels give one-to-one correspondence between each sender and receiver

RESOURCES