【发布时间】:2013-08-02 13:37:28
【问题描述】:
我偶尔会看到一种模式,其中gen_server 进程的init/1 函数将向自身发送一条消息,表明它应该被初始化。这样做的目的是让gen_server 进程异步初始化自身,以便生成它的进程不必等待。这是一个例子:
-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.
该过程假定init 消息将在任何其他消息之前被接收 - 否则它将崩溃。这个过程是否有可能在init消息之前得到m消息?
假设没有进程向list_to_pid 生成的随机 pid 发送消息,因为无论此问题的答案如何,任何执行此操作的应用程序都可能根本无法工作。
【问题讨论】:
-
我无法判断这些答案是否正确,因为它们似乎都假设这个问题是正确的:stackoverflow.com/q/18018780/2213023
标签: concurrency erlang