【问题标题】:Creating a Supervisor having multiple children elixir创建一个有多个孩子的主管长生不老药
【发布时间】:2019-03-08 06:04:27
【问题描述】:

我正在尝试从用户那里获取输入,然后创建 genservers 的数量作为输入并监督它们。我的代码类似于

defmodule GossSim do
  use Supervisor

def main(args) do
  # Since it is a mix generated project I had to put the main
  Supervisor.start_link(__MODULE__, args)
end

def start_link(args) do
  Supervisor.start_link(__MODULE__, args)
end

#The two methods down below create children dynamically
def get_child_list(child_list, 0), do: child_list

def get_child_list(child_list, num_of_nodes) do
  child = 
    %{  
    id: :rand.uniform(num_of_nodes*100000),
    start: {Gossip_node, :start_link, [[0,true]]}
  }  
  if num_of_nodes > 0 do

    get_child_list( [child] ++ child_list, num_of_nodes-1)
  end
end

def init(args) do
  children = get_child_list([], 10)
  # The outut of this inspect is pasted below
  IO.inspect children, label: "The children list is"
  // some function that does something parse_args_and_start(args)
  // num_of_nodes is 10
  children = get_child_list([], num_of_nodes)
  Supervisor.init(children, strategy: :simple_one_for_one)

end

我收到以下错误

bad child specification, invalid children: [%{id: 512, start: {Gossip_node, :start_link, [[0, true]]}, type: :worker}, %{id: 49677, start: {Gossip_node, :start_link, [[0, true]]}, type: :worker},

后面是所有子进程的列表。进程有不同的ID

主管文档说,如果主管有一个开始和一个 ID,它就很好。由于孩子是一个列表,我在其中添加了多个孩子的地图。我是不是错过了什么。 Gossip_node 是同一文件夹中的一个模块。

【问题讨论】:

    标签: elixir erlang-supervisor gen-server


    【解决方案1】:

    :simple_one_for_one 策略已弃用,取而代之的是 DynamicSupervisor

    无论如何,让我们快速浏览一下docs 未被弃用的情况:

    :simple_one_for_one - 类似于 :one_for_one 但更适合动态附加孩子。此策略要求主管规范仅包含一个孩子。

    因此,您需要将主管的策略更改为:one_for_one(或其他一些):

    Supervisor.init(children, strategy: :simple_one_for_one)
    

    或创建一个有一个孩子的主管(或者如果使用DynamicSupervisor,则没有孩子)并动态附加每个孩子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2010-09-16
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多