Skip to main content

Actor-owned state

These two counters start at zero. Each owns its count, so messages to one leave the other unchanged. Run the program and compare their totals.

Try a change

Change left.add(3) to right.add(3). Predict the two totals before you run it.

state.hew

actor Counter {
    var count: i64 = 0;
 
    receive fn add(n: i64) {
        count = count + n;
    }
 
    receive fn value() -> i64 {
        count
    }
}
 
fn main() {
    let left = spawn Counter;
    let right = spawn Counter;
    _ = left.add(5);
    _ = right.add(2);
    _ = left.add(3);
 
    let a = left.value().expect("left counter stopped");
    let b = right.value().expect("right counter stopped");
    println(f"Left: {a}");
    println(f"Right: {b}");
}
Continue in playground (new tab) ↗ Your edits open in a new tab.

Press Escape to leave the editor. runs your code.

Output

Run the example to see its output.

Expected from the original example

Left: 8
Right: 2

The state belongs to the actor

Both actors use the Counter definition, and each has its own count. Calling left.add(3) changes the left counter through its handler. Calling right.add(3) changes the right one.

add changes the receiving actor's count; value reads it. These ordinary calls wait for their handlers, so the final reads happen after the increments.

The _ = lines deliberately ignore the acknowledgements from the three increments. The two reads use expect to stop the program if a counter cannot reply. For calls whose failures you want to handle, use match, as in the messages experiment.

Several callers, one actor

An actor processes its messages one at a time. Your program still needs to account for the order of messages from independent callers. The actor model guide explains calls that wait for a reply and explicitly queued work.

Run it on your machine

Install Hew, then download an example and run it from the folder where you saved it.

macOS / Linux

hew build state.hew -o state && ./state

Windows PowerShell

hew build state.hew -o state.exe
.\state.exe