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

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

My Genserver:

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

  def create_table(pid, table) do, {:create_table, table})

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


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}})

You can read more info in:

:your_registry_name may be started under your application supervisor.


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.

1 Like

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.