What is ref in Erlang?

前端 未结 4 1812
忘掉有多难
忘掉有多难 2021-01-12 08:00

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

4条回答
  •  囚心锁ツ
    2021-01-12 08:43

    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:

    1. critic ! Message
    2. critic receives
    3. critic replies
    4. critic dies
    5. whereis fails
    6. critic is restarted
    7. code crashes

    or

    1. critic ! Message
    2. critic receives
    3. critic replies
    4. critic dies
    5. critic is restarted
    6. whereis picks up wrong pid
    7. message never matches

    There 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.

提交回复
热议问题