0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · Lección

Patrones básicos de concurrencia

Implemente aplicaciones concurrentes sencillas mediante la creación de procesos y la recepción de mensajes, y explore patrones básicos como las interacciones cliente-servidor.

Patrones básicos de concurrencia es una lección gratuita de Erlang OTP: Distributed & Fault-Tolerant Systems Programming en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Erlang OTP: Distributed & Fault-Tolerant Systems Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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.

Preguntas frecuentes

¿La lección «Patrones básicos de concurrencia» es gratis?

Sí — el texto completo de «Patrones básicos de concurrencia» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming, actualiza a CoddyKit PRO. El curso de Erlang OTP: Distributed & Fault-Tolerant Systems Programming incluye 4 lecciones en total.

¿Qué aprenderé en «Patrones básicos de concurrencia»?

Implemente aplicaciones concurrentes sencillas mediante la creación de procesos y la recepción de mensajes, y explore patrones básicos como las interacciones cliente-servidor. Practicas Erlang OTP: Distributed & Fault-Tolerant Systems Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

No se requiere experiencia previa. Erlang OTP: Distributed & Fault-Tolerant Systems Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Patrones básicos de concurrencia»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Erlang OTP: Distributed & Fault-Tolerant Systems Programming?

Sí. Cada lección de Erlang OTP: Distributed & Fault-Tolerant Systems Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción a Erlang y la VM
  2. Procesos y mensajería en Erlang
  3. Patrones básicos de concurrencia
  4. Coincidencia de patrones y guards
← Volver a Erlang OTP: Distributed & Fault-Tolerant Systems Programming