Reputation: 2155
I have a worker that is initialised as follows:
defmodule GenServerDB.Worker do
use GenServer
def start_link(name) do
GenServer.start_link(__MODULE__, :ok, [name: {:global, {:name, name}}])
end
def init(:ok) do
{:ok, %{}}
end
end
I can then create workers that I expect to be named using the :global
module:
iex(3)> {:ok, pid} = Supervisor.start_link([Supervisor.Spec.worker(GenServerDB.Worker, [], [])], strategy: :simple_one_for_one)
{:ok, #PID<0.126.0>}
iex(4)> Supervisor.start_child(pid, [[1]])
Supervisor.start_child(pid, [[1]])
{:ok, #PID<0.128.0>}
iex(6)> Supervisor.start_child(pid, [[2]])
Supervisor.start_child(pid, [[2]])
{:ok, #PID<0.131.0>}
iex(7)> Supervisor.start_child(pid, [[3]])
Supervisor.start_child(pid, [[3]])
{:ok, #PID<0.133.0>}
iex(8)> Supervisor.which_children(pid)
Supervisor.which_children(pid)
[{:undefined, #PID<0.128.0>, :worker, [GenServerDB.Worker]},
{:undefined, #PID<0.131.0>, :worker, [GenServerDB.Worker]},
{:undefined, #PID<0.133.0>, :worker, [GenServerDB.Worker]}]
However when I try and get the pid
for a given name
, I get the following:
iex(9)> :global.whereis_name({:global, {:name, 1}})
:global.whereis_name({:global, {:name, 1}})
:undefined
Am I missing something here? It looks like I haven't named the process properly.
Upvotes: 1
Views: 1539
Reputation: 222158
You're using the argument in the :global.whereis_name/1
call. You don't need the {:global
here and the name of the process is actually {:name, [1]}
, so you need to call :global.whereis_name({:name, [1]})
.
defmodule GenServerDB.Worker do
use GenServer
def start_link(name) do
GenServer.start_link(__MODULE__, :ok, [name: {:global, {:name, name}}])
end
def init(:ok) do
{:ok, %{}}
end
end
{:ok, pid} = Supervisor.start_link([Supervisor.Spec.worker(GenServerDB.Worker, [], [])], strategy: :simple_one_for_one)
Supervisor.start_child(pid, [[1]])
Supervisor.start_child(pid, [[2]])
Supervisor.start_child(pid, [[3]])
IO.inspect Supervisor.which_children(pid)
IO.inspect :global.whereis_name({:name, [1]})
Output:
[{:undefined, #PID<0.77.0>, :worker, [GenServerDB.Worker]},
{:undefined, #PID<0.78.0>, :worker, [GenServerDB.Worker]},
{:undefined, #PID<0.79.0>, :worker, [GenServerDB.Worker]}]
#PID<0.77.0>
Upvotes: 3