【发布时间】:2013-02-01 15:06:13
【问题描述】:
我使用标准 IO 函数从 Learn you some Erlang 修改了厨房模块,以查看按执行顺序打印的内容,我发现了一些非常奇怪的东西。基本上我在shell中运行了以下内容
3> Pid = spawn(kitchen, fridge2, [[baking_soda]]).
<0.41.0>
4> kitchen:store(Pid, water).
0
2
1
ok
ok
在我看来,函数 store 在打印出 0 之后的 store 函数中的 receive 子句之前调用了函数 freezer2,然后在打印了 2 之后,执行了接收子句并最终打印了 1。修改后的代码如下。如何从 store 函数中调用冰箱函数?这是因为以某种方式并行执行吗?这行 {Pid, Msg} -> 在 store 函数中是做什么的?是函数调用吗?为什么可以打印?
-module(kitchen).
-compile(export_all).
start(FoodList) ->
spawn(?MODULE, fridge2, [FoodList]).
store(Pid, Food) ->
Pid ! {self(), {store, Food}},
io:format("~p~n", [0]),
receive
{Pid, Msg} ->
io:format("~p~n", [1]),
io:format("~p~n", [Msg]),
Msg
end.
take(Pid, Food) ->
Pid ! {self(), {take, Food}},
receive
{Pid, Msg} -> Msg
end.
store2(Pid, Food) ->
Pid ! {self(), {store, Food}},
receive
{Pid, Msg} -> Msg
after 3000 ->
timeout
end.
take2(Pid, Food) ->
Pid ! {self(), {take, Food}},
receive
{Pid, Msg} -> Msg
after 3000 ->
timeout
end.
fridge1() ->
receive
{From, {store, _Food}} ->
From ! {self(), ok},
fridge1();
{From, {take, _Food}} ->
%% uh....
From ! {self(), not_found},
fridge1();
terminate ->
ok
end.
fridge2(FoodList) ->
receive
{From, {store, Food}} ->
From ! {self(), ok},
io:format("~p~n", [2]),
fridge2([Food|FoodList]);
{From, {take, Food}} ->
case lists:member(Food, FoodList) of
true ->
io:format("~p~n", [3]),
From ! {self(), {ok, Food}},
fridge2(lists:delete(Food, FoodList));
false ->
io:format("~p~n", [4]),
From ! {self(), not_found},
fridge2(FoodList)
end;
terminate ->
ok
end.
【问题讨论】: