How to give GenServer process a name?

While starting a genserver process, I want to give it a name. As you can see in the following example pid is right now acting as a name for the genserver. How can i register table as the name of GenServer.
{:ok, pid} = start_base(). So if i pass table is start_base and then into BaseServer.startlink(), how can i modify my GenServer.start_link(), so that the table acts as the name of GenServer.

Here is my code:

def start_base() do
    BaseServer.start_link()
end

def creating_tables(tables_list) do
    Enum.map(tables_list, fn table ->
      {:ok, pid} = start_base()
      IO.puts("Pid of #{table} is #{inspect(pid)} ")
      BaseServer.create_table(pid, table)
    end)
  end

My Genserver:

# client
  def start_link do
    GenServer.start_link(__MODULE__, [])
  end

  def create_table(pid, table) do
    GenServer.call(pid, {:create_table, table})
  end

right now am passing the pid but how can I register it with the table name.

Thanks

The way to give dynamically a name to a genserver is using the Registry.

def start_link(table) do
    GenServer.start_link(__MODULE__, [], name: {:via, Registry, {:your_registry_name, table}})
  end

You can read more info in:

“https://hexdocs.pm/elixir/GenServer.html#module-name-registration”

:your_registry_name may be started under your application supervisor.

3 Likes

Thank you so much … i ll have a look at it.

You don’t necessarily need a Registry to do dynamic name registration. If your server name is an atom then the standard mechanism will work fine.

GenServer.start_link(__MODULE__, [], name: :"__MODULE__:#{table}")

Use Registry when you need non standard server name registration (so called via tuple). And Registry is just a one of implementations.

Yes. The standard way is the one you propose. But it generates dynamically atoms. If the goal is to start a lot of genserver on the fly, it could become problematic.

2 Likes

To be fair the “standard way” is also a registry. It’s just automatically running and doesn’t need wrapping in a via tuple for being the default. Though now I’m interested if there’s actually a speed difference between the two and if so how much it it.