Chuyển đến nội dung

Bài 36 · Projects and Practice

Practice: concurrency and OTP exercises

Twelve graded Erlang exercises on processes, message passing, receive timeouts, links, gen_server and supervisors, with hints, solutions and a runnable model.

Reading about processes is not enough; the model sinks in when you write a few. Erlang is not installed on this site, so install it locally (a package manager, the official installer or a container) and run these in erl, or write each exercise in a module and compile it with c(Module). The solutions are given in read-only blocks: try first, then compare. One exercise is also modelled in JavaScript so you can run it right here.

Warm-up

1. Echo. Write echo:start/0 that spawns a process which replies to {From, Msg} with {self(), Msg}, forever. Test by sending three messages.

ERLANG
-module(echo).
-export([start/0]).

start() -> spawn(fun loop/0).

loop() ->
    receive
        {From, Msg} -> From ! {self(), Msg}, loop()
    end.

2. Ping-pong. Start two processes that send ping and pong to each other 5 times and then stop, printing each step. Hint: pass the counter in the message; the process receiving 0 stops and tells its partner done.

3. Sequential versus parallel. Write parmap(F, List) that spawns one process per element, collects results in the original order and returns the list. Hint: tag each result with a make_ref(), spawn all first, then receive in list order.

ERLANG
parmap(F, List) ->
    Parent = self(),
    Refs = [begin
                Ref = make_ref(),
                spawn(fun() -> Parent ! {Ref, F(X)} end),
                Ref
            end || X <- List],
    [receive {Ref, Result} -> Result end || Ref <- Refs].

Because each receive matches on its own reference, the order of arrival does not matter.

Messages and timeouts

4. Timeout call. Write call(Pid, Request, Timeout) that returns {ok, Reply} or {error, timeout}. Use a reference so a late reply cannot be confused with a later answer.

5. Rate limiter. A process accepts {request, From} and replies ok at most 3 times per second. Over the limit it replies {error, too_many}. Hint: keep a list of timestamps (erlang:monotonic_time(millisecond)) in the loop state and drop entries older than 1000 ms.

6. Priority mailbox. Messages {high, X} must be handled before {low, X} even when they arrive later. Use the nested receive ... after 0 pattern.

Faults

7. Linked workers. Spawn three linked workers; one crashes after 100 ms. Show that the others die as well. Then trap exits in the parent and print the {'EXIT', Pid, Reason} message instead.

8. Monitor and retry. Write run_with_retry(Fun, Max) that runs Fun in a monitored process and retries when it crashes, up to Max times, returning {ok, Result} or {error, gave_up}. (Hint: the child sends {Ref, Result} on success; a DOWN with a non-normal reason means retry.)

ERLANG
run_with_retry(_Fun, 0) -> {error, gave_up};
run_with_retry(Fun, Max) ->
    Parent = self(),
    {Pid, Mon} = spawn_monitor(fun() -> Parent ! {self(), Fun()} end),
    receive
        {Pid, Result} ->
            erlang:demonitor(Mon, [flush]),
            {ok, Result};
        {'DOWN', Mon, process, Pid, _Reason} ->
            run_with_retry(Fun, Max - 1)
    end.

OTP

9. Counter as gen_server. Rewrite the counter from process loops and state as a gen_server with increment/0, value/0, reset/0. Add {ok, State, hibernate} and think about when it helps.

10. Stack server. A gen_server with push/1, pop/0 returning {ok, Value} or empty, and size/0. Add -specs and run rebar3 dialyzer (types and Dialyzer).

11. Supervised pool. Create a supervisor with simple_one_for_one that starts workers on demand (supervisors). Kill a worker with exit(Pid, kill) and confirm that a temporary worker is not restarted, while a permanent one is.

12. Cluster counter. Start two nodes (erl -sname a, erl -sname b), connect them, and call your counter on the other node with erpc:call (distributed nodes). Then kill node b and handle the noconnection error gracefully.

Run one in the browser: rate limiter model

This is a JavaScript model of exercise 5 (not Erlang): the process holds a list of recent timestamps in its state and decides per request. A virtual clock makes the output deterministic.

JS Stand-in: rate limiter process

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try changing the limit or window and predict the output before running.

A parallel map model

Exercise 3 can also be modelled: each element runs "in its own process" and finishes in a random order, yet the result list stays in the input order because replies are matched by reference.

JS Stand-in: parmap keeps order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Where to go from here

You have covered processes, messages, faults, OTP, distribution and tooling. To keep growing:

  • Read the source of real OTP modules (gen_server.erl, supervisor.erl); they are well documented and short.
  • Study a production library such as cowboy or ranch to see supervision trees in practice.
  • Learn ETS in depth (ordered_set, match_spec), then mnesia for a distributed database.
  • Try Elixir, which runs on the same virtual machine and uses the same OTP.
  • Practise thinking in failures: for every feature, decide what happens when a process dies, a message is lost or a node disappears.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. In parmap, why does the result list keep its input order?

    Receiving by reference in the original order reassembles results regardless of arrival order.
  2. 2. Which pattern implements a high-priority message check without blocking?

    after 0 falls through immediately when no high-priority message is waiting.
  3. 3. A permanent worker under a supervisor is killed. What happens?

    permanent children are always restarted; with one_for_one, siblings are untouched.
  4. 4. What is the main reason to catch noconnection when using erpc:call?

    Network failures are normal in distributed systems and need an explicit policy.

Summary

  • Practise the core moves: spawn, send, receive with references and timeouts, monitor and retry.
  • Rewrite your hand-made loops as gen_servers and put them under supervisors.
  • Test failure paths on purpose: kill workers, drop nodes, flood mailboxes.
  • Read OTP's own source and real libraries to see the patterns at scale.

Next: Back to the Erlang tutorial

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.