There is a pattern I've seen occasionally where the init/1
function of a gen_server
process will send a message to itself signalling that it should be initialized. The purpose of this is for the gen_server
process to initialize itself asynchronously so that the process spawning it doesn't have to wait. Here is an example:
-module(test).
-compile(export_all).
init([]) ->
gen_server:cast(self(), init),
{ok, {}}.
handle_cast(init, {}) ->
io:format("initializing~n"),
{noreply, lists:sum(lists:seq(1,10000000))};
handle_cast(m, X) when is_integer(X) ->
io:format("got m. X: ~p~n", [X]),
{noreply, X}.
b() ->
receive P -> {} end,
gen_server:cast(P, m),
b().
test() ->
B = spawn(fun test:b/0),
{ok, A} = gen_server:start_link(test,[],[]),
B ! A.
The process assumes that the init
message will be received before any other message - otherwise it will crash. Is it possible for this process to get the m
message before the init
message?
Let's assume there's no process sending messages to random pids generated by list_to_pid
, since any application doing this will probably not work at all, regardless of the answer to this question.