开发者

Erlang Concurrency Model

This could be a very basic question but is Erlang capable of calling a method on another prcoess and wait for it to repond back with some ob开发者_开发百科ject type without sleeping threads?


Well, if you're waiting for an answer, the calling process will have to sleep eventually… But that's no big deal.

While processes are stuck on the receive loop, other processes can work. In fact, it's not uncommon to have thousands of processes just waiting for messages. And since Erlang processes are not true OS threads, they're very lightweight so the performance loss is minimal.

In fact, the way sleep is implemented looks like:

sleep(Milliseconds) ->
    receive
        % Intentionally left empty
    after Milliseconds -> ok
    end.


Yes, it is possible to peek into the mailbox if that is what you mean. Say we have sent a message to another process and now we want to see if the other process has sent something back to us. But we don't want to block on the receive:

 receive
    Pattern -> Body;
    Pattern2 -> Body2
 after 0 ->
    AfterBody
 end

will try to match against the Pattern and Pattern2 in the mailbox. If none matches, it will immediately time out and go to AfterBody. This allows you to implement a non-blocking peek into the mailbox.

If the process is a gen_server the same thing can be had by playing with the internal state and the Timeout setting when a callback returns to the gen_server's control. You can set a Timeout of 0 to achieve this.


What am getting from the question is that we are talking of Synchronous Message Passing. YES ! Erlang can do this perfectly well, its the most basic way of handling concurrency in Erlang. Consider this below:

rpc(Request, To)->
  MySelf = self(),
  To ! {MySelf,Request},
  receive
     {To,Reply} -> Reply
  after timer:seconds(5) -> erlang:exit({error,timedout})
  end.

The code above shows that a processes sends a message to another and immediately goes into waiting (for a reply) without having to sleep. If it does not get a reply within 5 seconds, it will exit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜