Task

As we saw earlier, processes are cheap to spawn in Elixir because we are always in the realm of the BEAM. This is the perfect setup for us to spawn a process whenever we need. If you need to do something in parallel, you can spawn a process. If you need to do many things in parallel, you can spawn many processes. The virtual machine won't break a sweat and you will have an army of processes in no time to accomplish whatever you need.

However, process communication is laborious, so if you need results from those parallel computations, you will have to receive the results via message passing and eventually terminate the processes afterwards.

In this situation, we can resort to the Task module, using its Task.async/1 function to spawn tasks, ...

Get Mastering 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.