Back to Examples

Inter-worker message passing

Use -> W or <- W to send a message to or receive a message from worker W (use function to refer to the function's default worker). The messages are copied using clone(). It implies immutable values are passed without a copy.

Message sends and receives are paired up at compile-time. Each pair turns into a horizontal line in the sequence diagram. Easy to use and safe, but limited expressiveness.

import ballerina/io;

public function main() {

    worker A {
        // Use `-> W` to send a message to worker `W`.
        1 -> B;
        2 -> C;
    }

    worker B {
        // Use `<- W` to receive a message from worker `W`.
        int x1 = <- A;

        // Use `function` to refer to the function's default worker.
        x1 -> function;
    }

    worker C {
        int x2 = <- A;
        x2 -> function;
    }

    int y1 = <- B;
    int y2 = <- C;

    io:println(y1 + y2);
}
$ bal run inter_worker_message_passing.bal3
PreviousNamed workers and futures
NextAlternate receive