6.28.1.5 Message queues

Gforth’s message queues are a variant of the actor model.

The sending task tells the receiving task to execute an xt with the stack effect ( -- ) (an event in the name of the words below; the actor model would call these xts messages), and when the receiving task is ready, it will execute the xt, possibly after other xts from its message queue.

The execution order between xts from different tasks is arbitrary, the order between xts from the same task is the sending order.

In many cases you do not just want to pass the xts of existing words, but also parameters. You can construct execute-once closures (defined using :}h1, see Closures) to achieve that, e.g., with

: .-in-task ( n task -- )
  >r [{: n :}h1 n . ;] r> send-event ;

5 my-task .-in-task \ my-task prints 5
send-event ( xt task –  ) gforth-experimental “send-event”

Inter-task communication: send xt ( -- ) to task. task executes the xt at some later point in time. To pass parameters, construct a one-shot closure that contains the parameters (see Closures) and pass the xt of that closure.

In order to execute xts received from other tasks, perform one of the following words in the receiving task:

?events ( ) gforth-experimental “question-events”

Execute all event xts in the current task’s message queue, one xt at a time.

event-loop ( ) gforth-experimental “event-loop”

Wait for event xts and execute these xts when they arrive, one at a time. Return to waiting if no event xts are in the queue. This word never returns.

Alternatively, when a task is stopped, it is also ready for receiving xts, and receiving an xt will not just execute the xt, but also continue execution after the stop.