Search code examples
functional-programmingelixirerlang-otp

Message passing in Elixir


Recently I have started learning Elixir but I struggle a little bit on the implementation part. I think I did understand the concepts of supervisor and children but I am not so used to functional programming. Could you give me an example of implementation for such a scenario:

Root Supervisor supervises the processes A and B. B is also a supervisor for some other processes. A should constantly pass messages to B and B should be able to pass these messages to it's children. Also the children of B should be able to pass messages back to B. A and B should be constantly running.

Give me the simplest example of implementation for such scenario, or give me some clues on how to implement the message passing between parent-child, child-child. Take into consideration that I am using mix for the project. Also, A and B should use GenServer

For example, let's suppose inside the root supervisor I have something like this, but now I don't know how to pass message from A to B.

    use Supervisor

    def start_link(opts) do
      Supervisor.start_link(__MODULE__, :ok, opts)
    end

    def start(_type, _args) do
        children = [
          {A, [name: NameForA]},
          {B, [name: NameForB]}}
        ]
    
        opts = [strategy: :one_for_one, name: Supervisor]
    
        # See https://hexdocs.pm/elixir/Supervisor.html
        # for other strategies and supported options
    
        Supervisor.start_link(children, opts)
    end

My assumption is that I should somehow pass to B the PID of A to know where to send the messages, but I don't really know how can I get the PID like this. Maybe I should use another approach? Any kind of hint or tip is welcomed.


Solution

  • The destination process might be addressed by Process.dest() type, and names processes exist for exactly this purpose.

    In the example above, one might send messages to NameForA.

    On the other hand, in Supervisor behaviour is explicitly dedicated to supervising and not messing with direct message passing. That said, you’d probably need more complicated supervision tree.