Here is a simple application to illustrate the feautres I was talking about. A process sends a message to another process using the send construct: Pid ! Message. Even if the Pid doesn’t exist, the send will succeed. A process can block to receive a message by using the receive construct. The receive construct may also take an optional timeout value in millseconds, after which the “after” clause of the receive construct is executed.
-export([main/0, thread/0]).
main() ->
Pid = spawn(receive1, thread, []),
io:fwrite("Spawned new process _w_n", [Pid]),
Pid ! hello.
thread() ->
io:fwrite("This is a thread._n", []),
process_messages().
process_messages() ->
receive
hello ->
io:fwrite("Received hello_n"),
process_messages()
after 2000 ->
io:fwrite("Timeout._n")
end.
Process IDs do not have to refer processes running on the same machine as the processes can be distributed an remote machines. So you can spawn a process using the node name and use the returned process ID to send messages just as if it were a process on the local machine.
Pid = spawn(remote_node,process1, thread, []) Pid ! a_message
Pid ! a_message
Erlang handles the creation of the processes very efficiently. Here is a simple graph comparing Java, C#, Erlang comparing the time taken to create processes and asynchronous message passing.
It is quite clear that Java and C# can't compete with Erlang in this features. We have to realize that the world is going towards parallel processing even we don't accept Erlang as a language I think it will take place in the next decade.
To be continued ...