0Pricing
Elixir & Phoenix: Scalable Backend Development · Aula

Trabalho Concorrente com Task e Agent

Execute código em simultâneo e gira estados partilhados simples usando as abstrações Task e Agent baseadas em OTP.

Trabalho Concorrente com Task e Agent é uma aula grátis de Elixir & Phoenix: Scalable Backend Development no CoddyKit. Esta é a aula 4 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 Elixir & Phoenix: Scalable Backend Development, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Elixir & Phoenix: Scalable Backend Development inclui 4 aulas no total.

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

Beyond Raw spawn

You can start processes with spawn, but OTP gives higher-level tools. Task runs concurrent work and collects results cleanly.

Fire-and-Forget Tasks

Task.start/1 runs a function in a new process when you do not need the result.

Task.start(fn -> IO.puts("running in background") end)

Async and Await

Task.async/1 starts work and returns a struct; Task.await/1 blocks until the result is ready.

task = Task.async(fn -> 2 + 2 end)
result = Task.await(task)
IO.inspect(result)

Running Tasks in Parallel

Start several tasks, then await them all. The total time is roughly the slowest task, not the sum.

tasks = Enum.map(1..3, fn n ->
  Task.async(fn -> n * n end)
end)
IO.inspect(Enum.map(tasks, &Task.await/1))

Task.await_many

Task.await_many/1 waits for a list of tasks and returns their results in order.

tasks = for n <- 1..3, do: Task.async(fn -> n * 10 end)
IO.inspect(Task.await_many(tasks))

Timeouts

Task.await/2 takes a timeout in milliseconds (default 5000). If exceeded it exits, signalling the work took too long.

task = Task.async(fn -> :timer.sleep(50); :done end)
IO.inspect(Task.await(task, 1000))

Streaming Concurrency

Task.async_stream/3 maps a function over a collection concurrently with a bounded number of workers.

1..5
|> Task.async_stream(fn n -> n * n end)
|> Enum.map(fn {:ok, v} -> v end)
|> IO.inspect()

Introducing Agent

An Agent wraps mutable state behind a process, giving simple shared state without writing a full GenServer.

{:ok, pid} = Agent.start_link(fn -> 0 end)
IO.inspect(Agent.get(pid, & &1))

Updating Agent State

Agent.update/2 transforms the state; Agent.get/2 reads it. The agent serializes access for safety.

{:ok, pid} = Agent.start_link(fn -> 0 end)
Agent.update(pid, &(&1 + 5))
IO.inspect(Agent.get(pid, & &1))

get_and_update

Agent.get_and_update/2 reads and writes atomically, returning a value while changing state.

{:ok, pid} = Agent.start_link(fn -> 10 end)
old = Agent.get_and_update(pid, fn s -> {s, s + 1} end)
IO.inspect({old, Agent.get(pid, & &1)})

Task vs Agent vs GenServer

Choose the lightest tool:

  • Task for one-off concurrent work
  • Agent for simple shared state
  • GenServer when you need custom messages and lifecycle

Quick Check

Test your Task knowledge.

Recap

You ran concurrent code with OTP abstractions:

  • Task.async/await for concurrent work and results
  • Task.async_stream for bounded parallel mapping
  • Agent for simple, safe shared state
  • Pick Task, Agent, or GenServer by how much control you need

Perguntas Frequentes

A aula “Trabalho Concorrente com Task e Agent” é grátis?

Sim — o texto completo de “Trabalho Concorrente com Task e Agent” é 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 Elixir & Phoenix: Scalable Backend Development, atualize para CoddyKit PRO. O curso de Elixir & Phoenix: Scalable Backend Development inclui 4 aulas no total.

O que vou aprender em “Trabalho Concorrente com Task e Agent”?

Execute código em simultâneo e gira estados partilhados simples usando as abstrações Task e Agent baseadas em OTP. Você pratica Elixir & Phoenix: Scalable Backend Development 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 Elixir & Phoenix: Scalable Backend Development?

Nenhuma experiência prévia é necessária. Elixir & Phoenix: Scalable Backend Development 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 4 de 4.

Quanto tempo leva a aula “Trabalho Concorrente com Task e Agent”?

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 Elixir & Phoenix: Scalable Backend Development?

Sim. Cada aula de Elixir & Phoenix: Scalable Backend Development 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. Processos do Elixir e Passagem de Mensagens
  2. Implementação do Comportamento GenServer
  3. Supervisores e Estrutura de Aplicações
  4. Trabalho Concorrente com Task e Agent
← Voltar para Elixir & Phoenix: Scalable Backend Development