Agents and Tasks

Processes play a crucial role in Elixir. We have seen how processes model state changes. Processes are also used to enable concurrency and provide fault tolerance.

Elixir provides two abstractions, called agents and tasks, that are specializations of those use cases. Agents and tasks are supervised processes. An agent[44] is a process that handles state. An agent is perfect for keeping some shared state that is accessed by multiple processes in your application. Earlier in this chapter we implemented a counter using agents.

A task[45] is about supervised behavior. For example, to do two things concurrently, use Task.async/1 to spawn each task and Task.await/1 to wait for the result, like this:

 task1 = Task.async(​fn​ -> do_some_work() ...

Get Adopting Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.