Lavoro concorrente con Task e Agent
Esegua il codice in concorrenza e gestisca uno stato condiviso semplice usando le astrazioni Task e Agent, basate su OTP.
Lavoro concorrente con Task e Agent è una lezione Elixir & Phoenix: Scalable Backend Development gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Elixir & Phoenix: Scalable Backend Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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/awaitfor concurrent work and resultsTask.async_streamfor bounded parallel mappingAgentfor simple, safe shared state- Pick Task, Agent, or GenServer by how much control you need
Domande Frequenti
La lezione «Lavoro concorrente con Task e Agent» è gratuita?
Sì — il testo completo di «Lavoro concorrente con Task e Agent» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Elixir & Phoenix: Scalable Backend Development, passa a CoddyKit PRO. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.
Cosa imparerò in «Lavoro concorrente con Task e Agent»?
Esegua il codice in concorrenza e gestisca uno stato condiviso semplice usando le astrazioni Task e Agent, basate su OTP. Eserciti Elixir & Phoenix: Scalable Backend Development con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Elixir & Phoenix: Scalable Backend Development?
Non è richiesta alcuna esperienza precedente. Elixir & Phoenix: Scalable Backend Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Lavoro concorrente con Task e Agent»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Elixir & Phoenix: Scalable Backend Development?
Sì. Ogni lezione Elixir & Phoenix: Scalable Backend Development include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Processi Elixir e passaggio dei messaggi
- Implementazione del comportamento GenServer
- Supervisor e struttura delle applicazioni
- Lavoro concorrente con Task e Agent