SKILL.md
Erlang Concurrency
Introduction
Erlang's concurrency model based on lightweight processes and message passing enables building massively scalable systems. Processes are isolated with no shared memory, communicating asynchronously through messages. This model eliminates concurrency bugs common in shared-memory systems.
The BEAM VM efficiently schedules millions of processes, each with its own heap and mailbox. Process creation is fast and cheap, enabling "process per entity" designs. Links and monitors provide failure detection, while selective receive enables flexible message handling patterns.
This skill covers process creation and spawning, message passing patterns, process links and monitors, selective receive, error propagation, concurrent design patterns, and building scalable concurrent systems.
Process Creation and Spawning
Create lightweight processes for concurrent task execution.
%% Basic process spawning
simple_spawn() ->
Pid = spawn(fun() ->
io:format("Hello from process ~p~n", [self()])
end),
Pid.
%% Spawn with arguments
spawn_with_args(Message) ->
spawn(fun() ->
io:format("Message: ~p~n", [Message])
end).
%% Spawn and register
spawn_registered() ->
Pid = spawn(fun() -> loop() end),
register(my_process, Pid),
Pid.
loop() ->
receive
stop -> ok;
Msg ->
io:format("Received: ~p~n", [Msg]),
loop()
end.
%% Spawn link (linked processes)
spawn_linked() ->
spawn_link(fun() ->
timer:sleep(1000),
io:format("Linked process done~n")
end).
%% Spawn monitor
spawn_monitored() ->
{Pid, Ref} = spawn_monitor(fun() ->
timer:sleep(500),
exit(normal)
end),
{Pid, Ref}.
%% Process pools
create_pool(N) ->
[spawn(fun() -> worker_loop() end) || _ <- lists:seq(1, N)].
worker_loop() ->
receive
{work, Data, From} ->
Result = process_data(Data),
From ! {result, Result},
worker_loop();
stop ->
ok
end.
process_data(Data) -> Data * 2.
%% Parallel map
pmap(F, List) ->
Parent = self(),
Pids = [spawn(fun() ->
Parent ! {self(), F(X)}
end) || X <- List],
[receive {Pid, Result} -> Result end || Pid <- Pids].
%% Fork-join pattern
fork_join(Tasks) ->
Self = self(),
Pids = [spawn(fun() ->
Result = Task(),
Self ! {self(), Result}
end) || Task <- Tasks],
[receive {Pid, Result} -> Result end || Pid <- Pids].
