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() ​end​)
 task2 = Task.async(​fn​ -> do_more_work() ​end​)
 Task.await(task1)
 Task.await(task2)

We start two tasks concurrently and wait for both to finish. The Task.async function makes a couple of assumptions. By default, if do_some_work() or do_more_work() fail, the process that called them will fail too. That’s an explicit design choice: the async and await combination helps you add concurrency to sequential code without changing the code semantics. So if the previous code would fail if any of those functions failed, the concurrent code will fail too. That’s normally what you want.

The Task module also provides a wide range of APIs when those assumptions aren’t enough. The Task API can give you explicit control over how long to wait for a task to terminate, via Task.yield/2, or when to shut it down. You can use the Task module to control timeouts or determine how failure may affect the system.

As specialized solutions, agents and tasks are simple and readable, but sometimes processes need to juggle state, concurrency, and fault tolerance at the same time, so agents and tasks might not be enough. In such cases, we need full-blown processes without restrictions and those often take the shape of GenServers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.150.109