Suppose two processes A and B may send data to the same TCP socket. Is it a good idea to have a process C dedicated to synchronizing send
s to the socket?
Erlang code for process C:
-module('socket-sender').
-export([start_sender/1, sender/1]).
start_sender(Socket) ->
spawn('socket-sender', sender, [Socket]).
sender(Socket) ->
receive
{From, Data} ->
Result = case gen_tcp:send(Socket, Data) of
ok -> ok;
{error, Reason} -> disconnected
end,
From ! Result,
sender(Socket)
end.
When process A or B wants to send data to the TCP socket, it will send {self(), Data}
to the sender process C, and wait for response. If C responds with ok
, then things are good; if C responds with disconnected
, process A or B will terminate itself.
But there is one issue with the above sender
code: how would the sender
process terminate?