Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1903162
  • 博文数量: 217
  • 博客积分: 4362
  • 博客等级: 上校
  • 技术积分: 4180
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-20 09:31
文章分类

全部博文(217)

文章存档

2017年(1)

2015年(2)

2014年(2)

2013年(6)

2012年(42)

2011年(119)

2010年(28)

2009年(17)

分类: LINUX

2011-03-14 19:32:46

area_server.erl

-module(area_server).
-export([loop/0]).
loop() ->
    receive
        {rectangle, Width, Ht} ->
            io:format("Area of rectangle is ~p~n", [Width * Ht]),
            loop();
        {circle, R} ->
            io:format("Area of circle is ~p~n", [3.14*R*R]),
            loop();
        Other ->
            io:format("I do not know what the area of a ~p is ~n", [Other]),
            loop()
    end.


测试过程:
1> c(area_server).
{ok,area_server}
2> Pid = spawn(fun area_server:loop/0).
<0.39.0>
3> Pid ! {circle, 67}.
Area of circle is 14095.46
{circle,67}

第一次改进:


-module(area_server).
-export([loop/0, rpc/2]).
rpc(Pid, Request) ->
    Pid ! {self(), Request},
    receive
        Response ->
            Response
    end.
loop() ->
    receive
        {From, {rectangle, Width, Ht}} ->
            From ! {rectangle, Width*Ht},
            loop();
        {From, {circle, R}} ->
            From ! {circle, 3.14*R*R},
            loop();
        {From, Other} ->
            Error = "Sorry, error!",
            From ! {Error,Other},
            loop()
    end.

测试:
4> c(area_server).
{ok,area_server}
6> Pid = spawn(fun area_server:loop/0).
<0.53.0>
7> area_server:rpc(Pid, sockes).      
{"Sorry, error!",sockes,ok}

改进2:


-module(area_server).
-export([loop/0, rpc/2]).
rpc(Pid, Request) ->
    Pid ! {self(), Request},
    receive
        {Pid, Response} ->
            Response
    end.
loop() ->
    receive
        {From, {rectangle, Width, Ht}} ->
            From ! {self(), Width*Ht},
            loop();
        {From, {circle, R}} ->
            From ! {self(), 3.14*R*R},
            loop();
        {From,Other} ->
            From ! {self(), error, Other},
            loop()
    end.


测试:
2> c(area_server).
{ok,area_server}
3> Pid = spawn(fun area_server:loop/0).
<0.43.0>
4> area_server:rpc(Pid, {rectangle, 8, 6}).
48
改进3:

-module(area_server).
-export([start/0]).
start() ->
    Pid = spawn(fun loop/0),
    rpc(Pid, {rectangle, 8, 6}).
rpc(Pid, Request) ->
    Pid ! {self(), Request},
    receive
        {Pid, Response} ->
            Response
    end.
loop() ->
    receive
        {From, {rectangle, Width, Ht}} ->
            From ! {self(), Width*Ht},
            loop();
        {From, {circle, R}} ->
            From ! {self(), 3.14*R*R},
            loop();
        {From,Other} ->
            From ! {self(), error, Other},
            loop()
    end.


测试:
2> c(area_server).
{ok,area_server}
3> area_server:start().
48
4> area_server:start().
48
5>
阅读(1332) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2011-03-15 19:57:53

erlang---不能错过的盛宴 http://hi.baidu.com/my2008space/blog/item/89b6aa1f51b8510b413417da.html