[erlang-questions] A sender() BIF?

Richard O'Keefe ok@REDACTED
Mon Feb 22 01:51:52 CET 2010


On Feb 22, 2010, at 2:20 AM, Michael Turner wrote:

>
> It's conventional for certain purposes to make the first term of a
> message tuple be the sender, where the receiver needs to know.\

Hmm.  I've always put the 'tag' first, for readability.
I find
	receive {ok,Pid,Data} -> ...
much more readable than
	receive {Pid,ok,Data} ->

>
> Recently, I started wondering: why isn't the appropriate sender  
> already
> available within each receive scope, via a BIF (or even via some  
> special
> variable)?

One reason is "because it's not needed", and another has to be
"because the reply address isn't always the sender address".

Imagine some sort of load balancing scheme

	Client 1			Server 1
	...		Router		...
	Client m			Server n

where the router receives messages from clients and redirects them
to servers, and the servers send their replies straight back to
the clients.

Also, consider that sending a message to a process on another node
doesn't _always_ result in a proxy stub for the sending process
materialising on the other node.

> Does the idea of sender() violate encapsulation in some meaningful  
> way?
> As matters stand, a module just has to take it on faith that a Pid
> identified as sender in a message actually *is* the sender.

What it has to take on faith is that the Pid in a message
identifies the right process to *reply* to, which is different.

Consider the following scenario:

	Self = self(),
	My_Helper_Pid = spawn(fun () ->
	   do some long computation,
	   Other_Process ! {proceed_with,Self,Data}
	end),
	...
	receive {response,Other_Process,Result} -> ...

If Other_Process relied on sender(), it would send the message
to the wrong process.

Having learned about Unix IPC and sockets before Erlang, it took
me a while to appreciate the fact that the ONLY information a
process has about a message is the information right there in the
message, which is precisely the information the sender chose to
divulge.




More information about the erlang-questions mailing list