Is there a clever way to give messages different priorities?

冷暖自知 提交于 2019-12-05 00:39:32

问题


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:)



来源:https://stackoverflow.com/questions/8699498/is-there-a-clever-way-to-give-messages-different-priorities

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!