有一个聪明的方式给消息不同的优先级? [英] Is there a clever way to give messages different priorities?

查看:132
本文介绍了有一个聪明的方式给消息不同的优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想,我可以在与erlang进程交谈时,分配不同的消息不同的优先级。



我希望能够先处理高优先级的邮件,然后再优先处理一次。



我尝试过不同的方法,方法1:

  loop() - > 
收到
{high,Msg} - >
使用消息执行某些操作,
loop()
在0之后 - >
ok
end,
receive
{low,Msg} - >
使用消息执行某些操作,
loop()
在0之后 - >
loop()
结束。

这样做是很安静的。我想接收者必须查看所有消息,看看每次运行时是否有一个高消息。



方法2:



我也尝试做一个调解器类型的方法,其中首先将消息设置为前台,前台,然后将消息发送到高队列或低队列,然后最后一个工作者线程请求firsk的高队列作业,如果该队列没有任何内容,那么从低队列中,如下所示:





这有缺点必须等待请求到达不同队列的前端,也许某种优先级系统可以工作: - )



有更聪明的方式做这样的东西

解决方案

我认为这篇文章回答了你的问题:



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



基本上你想收到如下:

 收到
{hi_priority,Msg} - >消息
0 - >
收到
Msg - > Msg
end
end

由于Erlang的文档说0之后表示如果邮箱中没有匹配的(优先级)消息,则会立即发生超时。



我不知道有什么更聪明的方法:)


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?

解决方案

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

这篇关于有一个聪明的方式给消息不同的优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆