0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · Aula

Padrões básicos de concorrência

Implemente aplicativos concorrentes simples usando criação de processos e recebimento de mensagens, explorando padrões básicos como interações cliente-servidor.

Padrões básicos de concorrência é uma aula grátis de Erlang OTP: Distributed & Fault-Tolerant Systems Programming no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Erlang OTP: Distributed & Fault-Tolerant Systems Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Perguntas Frequentes

A aula “Padrões básicos de concorrência” é grátis?

Sim — o texto completo de “Padrões básicos de concorrência” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming, atualize para CoddyKit PRO. O curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming inclui 4 aulas no total.

O que vou aprender em “Padrões básicos de concorrência”?

Implemente aplicativos concorrentes simples usando criação de processos e recebimento de mensagens, explorando padrões básicos como interações cliente-servidor. Você pratica Erlang OTP: Distributed & Fault-Tolerant Systems Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

Nenhuma experiência prévia é necessária. Erlang OTP: Distributed & Fault-Tolerant Systems Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Padrões básicos de concorrência”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

Sim. Cada aula de Erlang OTP: Distributed & Fault-Tolerant Systems Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Introdução a Erlang e à VM
  2. Processos e troca de mensagens em Erlang
  3. Padrões básicos de concorrência
  4. Correspondência de Padrões e Guardas
← Voltar para Erlang OTP: Distributed & Fault-Tolerant Systems Programming