Elixir Multiple Processes

I’m having a hard time understanding how could I integrate processes in my application. I’ve done the Elixir Guide and I hope someone can help me understand this:

Can I have a process that spawns other processes for him to do his work? This “master” process sends two values a, b and an atom :add to some process, that process makes the sum and sends it back to the “master” process? I’m looking at all sorts of tutorials but can’t find any example in this matter.

Thank you.

It sounds like the Task.Supervisor could fit your needs, but maybe you could tell us more about what you really want to achieve (see http://xyproblem.info/)?

Hi for the “worker process” you can implement a Task or a GenServer, this is the link of Elixir Guide for the GenServer and this for the Task.

The shell is already a process. The magic words are spawn, and send. You might also want to learn about Link and Monitor, which are the basic blocks, on which OTP is built upon.

$ iex
Erlang/OTP 21 [erts-10.2.3] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]

Interactive Elixir (1.8.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> self()
#PID<0.107.0>
iex(2)> calculate = fn a, b, _action -> IO.puts(a + b) end
#Function<18.128620087/3 in :erl_eval.expr/5>
iex(3)> spawn fn -> calculate.(1, 2, :add) end
3
#PID<0.111.0>

This example just print some output, but You can pass self() as a parameter to the message, and have the spawned process send back the result to the calling process.

iex(1)> pid = self()  
#PID<0.107.0>
iex(2)> calculate = fn a, b, pid -> send(pid, {:result, a + b}) end
#Function<18.128620087/3 in :erl_eval.expr/5>
iex(3)> spawn fn -> calculate.(1, 2, pid) end
#PID<0.111.0>
iex(4)> flush
{:result, 3}
:ok

You might like

https://www.cs.kent.ac.uk/ErlangMasterClasses/

in particular Master class 2, which is about turning sequential programming into concurrent.

2 Likes

Sure, you could do that. Now, whether or not there is any actual advantage to doing that depends on other factors: do you have 2 or more cores such that a & b can actually run simultaneously, or do a or b or both reach a point where they are waiting on I/O such that the other one can run in the gap?

Elixir processes make it very easy (and practical) to spawn multiple processes to take advantage of those kinds of situations, so easy that you can do so when there might be a chance but you’re not sure that such a situation occurs. Elixir (Erlang, really) make it easy to deal with a HUGE number of different processes in those types of situations,

1 Like