0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · Урок

Базовые шаблоны конкурентности

Реализуйте простые конкурентные приложения с помощью создания процессов и приёма сообщений, а также изучите базовые шаблоны, например взаимодействие клиент–сервер.

«Базовые шаблоны конкурентности» — бесплатный урок Erlang OTP: Distributed & Fault-Tolerant Systems Programming на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Erlang OTP: Distributed & Fault-Tolerant Systems Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Erlang OTP: Distributed & Fault-Tolerant Systems Programming содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Concurrency Patterns in Erlang

Concurrency patterns are proven ways to structure how processes interact, so you build robust, predictable concurrent apps.

The Request-Response Pattern

The Request-Response pattern is a conversation: a client sends a request, the server does the work, then replies. The backbone of interactive services.

Building a Simple Server

A server process loops on receive, handling each message and replying with SenderPid ! Reply; self() gives it its own PID.

Code: Echo Server Example

This echo server receives any message, grabs the sender's PID, and sends the message right back tagged as echoed.

-module(echo_server).
-export([start/0, loop/0]).

start() ->
    spawn(echo_server, loop, []).

loop() ->
    receive
        {FromPid, Message} ->
            FromPid ! {self(), echoed, Message},
            loop();
        _ ->
            io:format("Server received unknown message.~n"),
            loop()
    end.

Code: Echo Client Interaction

The matching echo client spawns the server, sends {self(), msg} so the server knows where to reply, then waits for the response.

-module(echo_client).
-export([run/0]).

run() ->
    ServerPid = echo_server:start(),
    io:format("Server started with PID: ~p~n", [ServerPid]),

    Request = "Hello Erlang!",
    ServerPid ! {self(), Request},
    io:format("Client sent: ~p to server ~p~n", [Request, ServerPid]),

    receive
        {_ServerPid, echoed, Response} ->
            io:format("Client received reply: ~p~n", [Response]);
        _ ->
            io:format("Client received unexpected message.~n")
    after 5000 ->
        io:format("Client timed out waiting for reply.~n")
    end.

Running the Echo System

To run it, compile both modules and call echo_client:run() in the shell — a full request-response cycle across two processes.

The Asynchronous Pattern

The Asynchronous ("fire and forget") pattern: the client sends a message and moves on immediately while the receiver works in the background. Great for logging or jobs.

Code: Asynchronous Logger Process

This logger process just receives messages and prints them, sending no reply — the server side of the asynchronous pattern.

-module(async_logger).
-export([start/0, loop/0]).

start() ->
    spawn(async_logger, loop, []).

loop() ->
    receive
        {log, Message} ->
            io:format("LOG: ~p~n", [Message]),
            loop();
        _ ->
            io:format("Logger received unknown message.~n"),
            loop()
    end.

Code: Asynchronous Logger Client

The matching client spawns the logger, sends a message, and continues immediately without waiting — non-blocking by design.

-module(logger_client).
-export([run/0]).

run() ->
    LoggerPid = async_logger:start(),
    io:format("Logger started with PID: ~p~n", [LoggerPid]),

    LoggerPid ! {log, "User X logged in."},
    io:format("Client sent first log. Continuing...~n"),

    timer:sleep(10), % Give logger a moment to process
    LoggerPid ! {log, "User Y viewed profile."},
    io:format("Client sent second log. Task complete.~n").

Concurrency Pattern Check

You're building a system where a user uploads a large video. Your main process needs to immediately tell the user "Video uploaded, processing in background." while a separate process transcodes the video. What pattern best describes the interaction between the main process and the video transcoder?

Recap: Basic Concurrency Patterns

Recap: Request-Response waits for a reply (interactive work), while Asynchronous fires and forgets (background tasks). Your core concurrency toolkit.

Часто задаваемые вопросы

Урок «Базовые шаблоны конкурентности» бесплатный?

Да — полный текст урока «Базовые шаблоны конкурентности» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Erlang OTP: Distributed & Fault-Tolerant Systems Programming, подпишись на CoddyKit PRO. Курс Erlang OTP: Distributed & Fault-Tolerant Systems Programming содержит 4 уроков всего.

Чему я научусь в уроке «Базовые шаблоны конкурентности»?

Реализуйте простые конкурентные приложения с помощью создания процессов и приёма сообщений, а также изучите базовые шаблоны, например взаимодействие клиент–сервер. Ты практикуешь Erlang OTP: Distributed & Fault-Tolerant Systems Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

Предыдущий опыт не требуется. Erlang OTP: Distributed & Fault-Tolerant Systems Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Базовые шаблоны конкурентности»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

Да. Каждый урок Erlang OTP: Distributed & Fault-Tolerant Systems Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Введение в Erlang и VM
  2. Процессы и обмен сообщениями в Erlang
  3. Базовые шаблоны конкурентности
  4. Сопоставление с шаблонами и защитные условия
← Назад к Erlang OTP: Distributed & Fault-Tolerant Systems Programming