rap*_*cil 3 erlang message multiprocessing
我正在研究"学习一些Erlang"一书.我在使用Erlang进行多处理编程时有几个问题要实现.基本上,我正在阅读并模仿"了解你的一些二郎".我在程序中生成了一个带有一些导向函数的程序.它说冰箱可以像自己一样存放和拿走.所以我正在处理我的程序,以便在基本遵循以下的操作中执行某些操作:
首先,我需要终止消息应该与store和take相同的形式.这意味着消息应该是{from, terminate},接收者回复消息{self(), terminated}.
其次,我想通过消息回复发件人无组织{From, Msg}的消息{self(), {not_recognized, Msg}}.
第三,添加库存消息{From, {inventory} }将返回到FoodListsender2进程中的当前发送者(From).
第四,添加窥视消息{From, {peek, a} }将查看存储在该过程中的项目.如果存在时,将消息发送回发送器(从): {present, a}.如果不存在,将消息发送回发送器(从): {not_present, a}.
我对冰箱本身的使用感到困惑.我用教程中的示例代码想出了类似下面的内容:
-module(kitchen).
-compile(export_all).
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},
fridge2( [Food | FoodList] );
{From, {take, Food}} ->
case lists:member(Food, FoodList) of
true ->
From ! {self(), {ok, Food}},
fridge2(lists:delete(Food, FoodList));
false ->
From ! { self(), not_found},
fridge2(FoodList)
end;
terminate ->
ok
end.
store(Pid, Food) ->
Pid ! {self(), {store, Food}},
receive
{Pid, Msg} -> Msg
end.
take(Pid, Food) ->
Pid ! {self(), {take, Food}},
receive
{Pid, Msg} -> Msg
end.
start(FoodList) ->
spawn(?MODULE, fridge2, [FoodList]).
Run Code Online (Sandbox Code Playgroud)
此外,这里有一些我一直在想的问题:
我怎么能创建一个冰箱过程?或者它已经存在了?
我怎么能创建一个烹饪过程,将冰箱过程pid传递给它?
我怎么能把物品存放到冰箱然后睡几秒钟,最后我可以从冰箱拿出一件物品?
这可能不是最复杂的问题,但我找不到任何关于此的文档,所以我很感激你们中的一些人可能知道答案.
小智 5
回答你的问题:
- 我怎么能创建一个冰箱过程?或者它已经存在了?
kitchen:start/1从erlang shell或其他模块调用后,函数spawn(?MODULE, fridge2, [FoodList])将为您生成一个进程.有关更多详细信息,请查看文档:http://www.erlang.org/doc/man/erlang.html#spawn-3
- 我怎么能创建一个烹饪过程,将冰箱过程pid传递给它?
正如我在第一个答案中所说的spawn/3,它采用a module,a function和argumentsas参数,是可用于生成新进程的函数之一.因此,您应该使用它来生成一个接收kitchen:fridge2/1pid作为参数的进程,例如
Kitchen = kitchen:start([]),
Cook = spawn(cook_module, cook_function, [Kitchen]).
Run Code Online (Sandbox Code Playgroud)
这样你就会产生一个执行cook_module:cook_function/1并传递Kitchen(冰箱pid)作为参数的进程.
- 我怎么能把物品存放到冰箱然后睡几秒钟,最后我可以从冰箱拿出一件物品?
您可以使用该store/2功能将物品存放到冰箱中,稍等(或几秒钟,如您所愿),然后使用该take/2功能从冰箱取出一些东西.像这样:
Pid = kitchen:start([]), %% this will spawn a fridge process
kitchen:store(Pid, "delicious insect pie"), %% this will store a delicious insect pie in your fridge by executing the function fridge2( [Food | FoodList] );
timer:sleep(1000), %% this function will make the caller process sleeps for 1000 milliseconds (you can change it for your several seconds instead...)
kitchen:take(Pid, "delicious insect pie"). %% this will take the delicious insect pie out of the fridge, by executing the function fridge2(lists:delete(Food, FoodList));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |