《Erlang程序设计》第8章习题第一…

来源:互联网 发布:淘宝高达模型 编辑:程序博客网 时间:2024/06/07 00:38
(1)编写一个函数start(AnAtom,Fun)来把spawn(Fun)的结果注册为AnAtom。当两个并行的进行同时执行到start/2函数时,要确保代码能够正常工作。也就是说,这两个进程其中一个成功执行,而另一个必须执行失败。

-module(p150_1_process_conflict).
-export([main/0]).

%Not to concern about what the function Fun is.

main() -> %% ctreate two process.
start(wrong111,(fun() -> io:format("Wrong~n") end)),
%�d something to make sure there are not system output
start(ok111,(fun() -> io:format("Ok~n") end)).

start(AnAtom, Fun) ->  
    R =self(),
    spawn(fun()-> try register(AnAtom, R) of  
%%start should be registered in order to avoid two processesexecute start/2 in the same time.
                          true->  
                            R ! true,  
                            Fun()  
                    catch  
                        error:_ ->  R ! false 
                      end  
         end),  
   
    receive 
       true -> io:format("True~n");
       false -> io:format("False ~n")  
    end.


实际执行中会在末行多输出一个ok.目前不知道是什么原因,留待回头解决.实际上程序主体是别人的.我之前用的whereis()来控制,但没用.
0 0
原创粉丝点击