Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some usages for make_ref() function in elixir?

Tags:

elixir

I saw a code snippet making use of make_ref() and not sure about the usability of this function.

The hexdocs says:

Returns an almost unique reference.

The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes.

Inlined by the compiler.

But it does not really say when or why I should use it. Why would I use it and when should I use it? It seems to me that all it does is generate random numbers. Why can't I just use some sort of random number generator?

This is what it does on terminal:

iex(1)> make_ref()
#Reference<0.3569050097.3772514305.191818>
iex(2)> make_ref()
#Reference<0.3569050097.3772514305.191837>
iex(3)> make_ref()
#Reference<0.3569050097.3772514307.194286>
like image 626
Iggy Avatar asked Jun 11 '18 14:06

Iggy


2 Answers

:erlang.make_ref/0 returns a reference that is unique among connected nodes.

It is mostly the legacy of before-UUID era. That said, just the random generator won’t be sufficient enough: it should generate something unique across different machines.

UUID could be a good alternative for references unless you are concerned about the memory load: references are way more efficient.

Also, calling make_ref is [arguably] handier than dealing with kinda UUID generator.

like image 167
Aleksei Matiushkin Avatar answered Nov 18 '22 20:11

Aleksei Matiushkin


I've seen it used as a "uniqueness" flag when sending messages.

See this example from db_connection:

def run_child(mod, fun, state, opts) do
  ref = make_ref()
  arg = [mod, fun, ref, self(), state, opts]
  {:ok, pid} = Task.Supervisor.start_child(__MODULE__, __MODULE__, :init, arg)
  mon = Process.monitor(pid)
  send(pid, {:go, ref, mon})
  {pid, mon}
end

def init(mod, fun, ref, conn, state, opts) do
  # ...
  receive do
    {:go, ^ref, mon} ->
      # ...
  end
end

Here make_ref/0 is used to send a message which can only be received by the process knowing the reference. It's a relatively easy way to restrict process communication to a particular "scope".

Apart from that mudasobwa's answer is certainly correct.

like image 39
Sascha Wolf Avatar answered Nov 18 '22 21:11

Sascha Wolf