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
Disclaimer: My answer is mostly based on Learn You Some Erlang, in particular the link provided in the question.
The idea of using references is to uniquely identify a given message, so that you can match the messages and their responses - given that the response includes the reference sent in the original message.
We need to identify messages when using named processes that restart because, in this scenario, we can't rely on PIDs, due to concurrency. As is given in the book:
critic ! Message
critic
receivescritic
repliescritic
dieswhereis
failscritic
is restartedor
critic ! Message
critic
receivescritic
repliescritic
diescritic
is restartedwhereis
picks up wrong pidThere are interleavings where you'll get the wrong PID, or no PID at all, leaving your process unable to receive a response, if it was expecting a response of the form {Pid, Response}
. This is a consequence of using named processes that restart: you know their PID might change without notice, unlimited times, hence naming them as a convenience to send them messages.
Using a unique identifier to tag the message avoids this problem altogether, because you expect the reference to be returned in the response, not a PID.
This question might explain why I use the italics in unique. The references are not really unique, but unique enough for practical purposes.