Processes and IPC

Niue allows several code blocks to execute parallelly. A concurrently executing code block is known as a process and is assigned a process id (pid). All code blocks run within the context of an instance of org.niue.Niue. Each Niue instance can theoretically execute up to 2147483645 simultaneous processes, but in practice, constraints on system resources limit this number. All processes within an instance of Niue shares a dynamic pool of system threads.

A process is spawned using the !! special word. This operation returns the pid of the new process. Processes use pids and the send/recv operations to exchange data. Let us look at a few examples of process spawning and inter-process communication:

( add 3 and 4 on a new process )
[ 3 4 + . ] !!
=> 7
. ( we will have the new process id on our stack )
=> 1
( make the new process wait till 2 values arrive on its
stack )
[ 2 recv + . ] !!
.
=> 2 ( we have the new pid on our stack )
10 20 ( send these ) 2 ( values to the process ) 2 send
=> 30 ( result computed by the process )
( an addition "server" process, that waits for two values
and prints their sum. )
[ [ ( ignore the count pushed by "times" ) , 2 recv + . ] 5
times ] !! 'pid ;
pid .
=> 3
3 4 2 pid send
=> 7
10 20 2 pid send
=> 30

Instead of printing the result, the child process can push the result to the parent's stack:

[ [ , 3 recv + swap 1 swap send ] 5 times ] !! 'pid ;
10 20 self 3 pid send ( send 10 and 20 along with the
process id (self) to receive
the result )
.
=> 30

Niue and thread safety

Though the Niue language provide concurrency, the Niue library itself is not thread safe. That means, an instance of the Niue virtual machine is not meant to be shared by multiple threads without proper synchronization. Make sure that the virtual machine is never required to execute two instructions parallelly.