Is there a clever way to give messages different p

2019-03-28 05:05发布

问题:

I've been thinking, I would like to able to assign different messages different priorities when talking to an erlang process.

I would like to be able to first handling high-priority messages, and then low-priority once.

I've tried different approaches, approach 1:

loop() ->
    receive 
        {high, Msg} ->
            Do something with the message, 
            loop()
        after 0 -> 
            ok
    end,
    receive 
        {low, Msg} ->
            Do something with the message, 
            loop()
        after 0 ->
            loop()
    end.

This does the job, but it is quiet slow. I guess the receive has to look through all the messages to see if there is a 'high' message everytime it runs.

Approach 2:

I've also tried doing a mediator type approach where a message was first set to a 'front-desk' the 'front-desk' then sent the message to either high-queue or low-queue, and then finally a 'worker' thread requested jobs from firsk the high-queue, and if that queue has nothing, then from the low-queue, as ilustrated here:

This had the downside of having to wait for the request to get to the front of the different queues, perhaps some sort of priority system would work :-)

Is there a smarter way of doing something like this?

回答1:

I think this paper answers your question:

https://www.erlang-solutions.com/upload/docs/9/erlang11-nystrom.pdf

Basically you want to have a receive as follows:

receive
  {hi_priority, Msg} -> Msg
after 0 ->
  receive
    Msg -> Msg
  end
end

As Erlang's documentation says "after 0" means that the timeout will occur immediately if there are no matching (priority) messages in the mailbox.

I am not aware of any smarter way of doing it:)



标签: erlang