Erlang: priority receive

感情迁移 提交于 2019-12-05 06:42:51

Erlang being a radically concurrent language, there's no reason you couldn't have been sent several messages at the exact same time. Making assumptions along the lines of "Oh, this is fast -- it's so unlikely other threads would do something that conflicts in that little time" is essentially the same thing as closing your eyes and saying "There's no such thing as race conditions, there's no such thing as race conditions..."

On (1): Whether this assumption can be made depends on details of your situation. For example, all other processes may have been waiting for something to happen before sending you their messages.

On (2): In fact, it seems to me that the worst case would be no priority messages, as the mailbox would have to be traversed every time: "Has a priority message come in yet?"

According to the erlang reference manual receive traverses the mailbox in time order. and blocks till a message matches the one of the clauses.

Given that it sounds like the inner recieve is going to block till it recieves a matching message. Because of this you might actually stack up priority messages while waiting for non-priority messages which is the opposite of what you want.

Too ways out of this predicament are throwing a new after clause on the inner receive. Or always match in the inner recieve.

Although looking at their function the inner clause should always match but I'm guessing this is what they were talking about.

The statement you highlight is simply saying that if you are in the blocking inner receive block you could process a low priority message before a high priority message (because you are matching everything) which is not necessarily the intent.

It's a bit of an edge case - I've found that being efficient at processing the messages when you want some type of filtering is important. In other cases I've also monitored the process queue depth and altered my strategy accordingly. As an example of the latter a simple logging gen_server type process (which used cast to send the log message) could get rather backed up as writing the log messages to disk can be a lot slower than pushing the messages to the process. If the queue depth got too large I would discard the informational/spam type messages that I would normally log and only process (write to disk) the critical ones.

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