March 2018
Intermediate to advanced
244 pages
6h 10m
English
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() ... |
Read now
Unlock full access