Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
Like this article? We recommend

Process Creation

As I mentioned earlier, Erlang is designed for highly concurrent systems. The spawn function executes a given function in parallel. The ! primitive is used to send messages. The syntax is very simple:

Process ! message.

This instruction sends message to the specified Process, a pid value returned by spawn. Note that the syntax is the same, irrespective of whether Process is running on the local machine, another machine in a cluster, or another machine somewhere on the Internet. The message can be any type understood by Erlang, but it’s common to send a tuple, the first value of which is the type of the message. This technique allows pattern matching to be used to filter the messages.

The receive statement is used to get the next message from the message queue. It supports the same pattern-matching syntax as the rest of Erlang. The following snippet shows a fragment of code used to reply to pings and log ping replies:

receive
    {ping, {Sender,Sent}} ->
       Sender ! {ack, {Sent, now()}}
    ;
    {ack, {Sent, Received}
       logRoundTrip(Sent, Received}
end

As before, the message type is used for pattern matching. Recall that variables begin with capital letters; the values of Sender, Sent, and Received are filled in when a message matching the stated part of the pattern is received.

  • + Share This
  • 🔖 Save To Your Account