[erlang-questions] Parse-transforming !! to a function call

Mats Cronqvist mats.cronqvist@REDACTED
Fri Aug 24 10:34:10 CEST 2007


On 2007-08-16 11:07, Richard Carlsson wrote:
> I'd like to encourage everyone on
> this list to keep thinking about how Erlang process communication could
> be made even simpler and more streamlined. Plain asynchronous message
> passing (with selective receive) is a powerful yet simple building block
> but it is still rather primitive, and often, Erlang programmers (myself
> included) will neglect to think too far about what might happen if
> messages are lost, timeouts occur, or messages arrive in an unexpected
> order. We tend to go back and fix those bugs when they bite us, but it
> would be better if we were using communication constructs that came with
> certain guarantees to begin with; like the difference between goto-
> programming and structured language constructs like while/for/case.

   i read somewhere that "an idiom indicates a missing feature." (or 
maybe i just made it up?)
   in any case, i tend to use this idiom a lot, and i think it does 
indeed indicate a missing language feature.

safe_send(Pid,Msg) ->
   Ref = erlang:monitor(process,Pid),
   Pid ! {Ref,self(),Msg},
   receive
     {'DOWN',Ref,_,_,R} ->
        exit({no_receiver,R,Pid});
     {Ref,Ans} ->
        erlang:demonitor(Ref),
        receive {_,Ref,_,_,_} -> ok after 0 -> ok end,
        Ans
   end.

   the caller of safe_send/2 will receive either an answer from Pid, or 
an exit(*).

   i'm not proposing safe_send/2 to become part of OTP (i haven't even 
compiled this particular version). my point is just that there is a need 
for a version of '!' that guarantees that the message was delivered.

   mats

(*)
   of course, the code running in Pid must look something like this;

   receive {Ref,Pid,Msg} -> Pid ! {Ref,handle(Msg)} end





More information about the erlang-questions mailing list