Ring of processes in Elixir

138 Views Asked by At

I need help with this elixir ring

I need to create an elixir function start/3 that receives a number of processes(n), a number of messages(m), and a message that will be sent a number m times to the rest of process in the ring. When the message has been passed m times the processes should die after that.

  def start(nproc,mtimes,msg) do
    pid = spawn fn ->
      first_proc(self(),mtimes,nproc - 1,msg)
    end
  end

  defp first_proc(firstPid,mtimes,nproc,msg) do
    pidAux = self()
    nextPid = spawn fn ->
      proc_start(firstPid,pidAux,mtimes,nproc,msg)
    end
    lastPid = receive do
      {pid, :ready} -> pid
    end
    prueba(lastPid,nextPid)
  end

  defp proc_start(firstPid,prevPid, contMess,counterProc,msg) when counterProc > 1 do
    pidAux = self()
    nextPid =  spawn fn ->
      proc_start(firstPid,pidAux,contMess,counterProc - 1,msg)
    end
    prueba(prevPid,nextPid)

  end

  defp proc_start(firstPid, prevPid,contMess, _, msg ) do
    send(firstPid,{self(),:ready})
    send(firstPid,{:print,contMess - 1,msg})
    prueba(prevPid,firstPid)

  end

  defp prueba(prev_proc, post_proc) do
    receive do
      {:end,_,msg} -> send(prev_proc,{:end,0,msg})
                      :ok
      {:print, 0,msg} -> send(prev_proc,{:end,0,msg})
                      :ok
      {:print, cont,msg} ->
                        send(post_proc,{:print,cont-1,msg})
                        prueba(prev_proc,post_proc)
    end
  end


end

but it seems the number of messages that pass is incorrect. This is the typical ring of messages in erlang but I don't know how to implement this problem Thanks for your help in advance

0

There are 0 best solutions below