Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ref in Erlang?

Tags:

erlang

Going through this link

To identify a process,we would be using a Pid. When should a ref be used?

I see this often while message sending/receiving but unable to interpret what role it plays in message interaction.

like image 876
HIRA THAKUR Avatar asked Oct 13 '14 10:10

HIRA THAKUR


People also ask

What is spawn in Erlang?

spawn() creates a new process and returns the pid. The new process starts executing in Module:Name(Arg1,...,ArgN) where the arguments are the elements of the (possible empty) Args argument list.

What is process dictionary in Erlang?

Erlang has something called Process Dictionary which is a sort of Key/Value store that belongs to each Erlang process. We can use it to store values in a simple manner inside Erlang programs while avoiding the limitations of Pure Functional Programming. The anti-flames suit is sold separately tho.

How do I terminate a process in Erlang?

A process can terminate itself by calling one of the BIFs exit(Reason), erlang:error(Reason), erlang:error(Reason, Args), erlang:fault(Reason) or erlang:fault(Reason, Args). The process then terminates with reason Reason for exit/1 or {Reason,Stack} for the others.

Is process alive Erlang?

This is called as is_process_alive(Pid). A Pid must refer to a process at the local node. It returns true if the process exists and is alive i.e., whether it is not exiting and has not exited. Otherwise, returns false.


2 Answers

To quote documentation

A reference is a term which is unique in an Erlang runtime system, created by calling make_ref/0.

This means that this is special data type, it's not an integer, not a list, and not a binary. Especially with unique prosperity. It's designed mostly to recognize some places in code. make_ref(), no matter where it is called, will return new value (in boundaries of it's size of course). And just like Fred describes in it's book, it is great for tagging messages, and recognizing if message we receive is in response to one we just send.

like image 132
mpm Avatar answered Sep 21 '22 22:09

mpm


In complement to other responses, beware that a ref:

  • is not a random value (just start a VM an type make_ref(). several times)
  • is unique only in one VM (open a new VM and type make_ref() several times, you will get the same result as above) Nevertheless you can create one using a tuple {node(),make_ref()}.

No discrepancy with the documentation, but I made some wrong assumption in the past ... :o). Thanks @Robert for correction!

like image 34
Pascal Avatar answered Sep 21 '22 22:09

Pascal