Concurrency
Concurrency is a huge part of the Erlang programming language and the following is an example of its usage.
The following is a .erl file that runs multiple processes, or threads, at the same time.
-module(concurr).
-author("kclick").
%% API
-export([start/0, count/1]).
count(0) ->
done;
count(N) ->
io:format("~p~n", [N]),
count(N - 1).
start() ->
spawn(concurr, count, [10]),
spawn(concurr, count, [15]),
spawn(concurr, count, [8]).
The result from running the program:
When each process reaches 1 the program stops. The third processes continues through 5, 4, 3, 2, and 1. The <0.235.0> is the process ID of the last call in the start function which was spawn(concurr, count, [8]). Also, with Erlang the processes can send messages between each other, a way to work amongst each other. This is known as message passing.
This is a short program demonstrating message passing. There are three functions ping, pong, and pang. Ping runs N times before finishing while Pong waits for Ping to run, and Pang waits for Pong to run.
-module(messaging).
-author("kclick").
%% API
-export([start/0, ping/2, pong/1, pang/0]).
ping(0, Pong_PID) ->
Pong_PID ! finished,
io:format("ping finished~n", []);
ping(N, Pong_PID) ->
Pong_PID ! {ping, self()},
io:format("Pinged~n"),
ping(N - 1, Pong_PID).
pong(Pang_PID) ->
receive
finished ->
Pang_PID ! finished,
io:format("Pong finished~n", []);
{ping, Ping_PID} ->
io:format("Pong received ping~n", []),
Pang_PID ! {pong, self()},
pong(Pang_PID)
end.
pang() ->
receive
finished ->
io:format("Pang finished~n", []);
{pong, Pong_PID} ->
io:format("Pang received Pong~n", []),
pang()
end.
start() ->
Pang_PID = spawn(messaging, pang, []),
Pong_PID = spawn(messaging, pong, [Pang_PID]),
spawn(messaging, ping, [5, Pong_PID]).
The function ping/2 sends a message, known as sending an atom, to pong/1 with Pong_PID ! {ping, self()}, pong/1 waits for that message with {ping, Ping_PID}, and after pong/1 sends a message to pang/0 and pang/0 waits for that message in the same way. In this example, ping is not waiting for any process but pong and pang are. When each process is finished, an atom finished is received by the next process.ping will finish first, pong second, and pang last. This is from running that program:
Typically, a process on one device is waiting for processes on other devices.