今天学习erlang的进程,并发编程。erlang的并发编程很简单,只有三个原语:
1)产生进程, spawn
2) 发送消息 !
3) 消息接收 receive ... end
erlang进程之间通过消息进行传递。

   今天用一个进程字典作为联系,也就是put,get. 向目标进程插入数据,然后查询数据,就那么简单。
代码如下:
 

-module(servertest).
-export([start/0, stop/0, myget/1, myset/2]).

%insertdata()->
%  put(zhangsanfeng, {age,18,sex,man}),
%  put(zhangwuji, {age,25,sex,man}),
%  put(linghuchong, {age,34,sex,man}),
%  put(miejueshitai, {age,34,sex,woman}).

%开启服务
start()->
  register(testserver, spawn(fun loop/0)).

%结束服务
stop()->
  testserver!stop.

%查询进程字典
myget(Key)->
  testserver!{self(), get, Key},
  receive 
    {_Pid, Response} ->
        Response
  end.  

%设置进程字典
myset(Key, Value)->
  testserver!{self(), set, Key, Value},
  receive 
    {_Pid, Response} ->
        Response
  end.  

%主循环代码
loop()->
  receive
  	{From, get, Key} -> 
  	   From!{self(), get(Key)},
  	   loop();
  	{From, set, Key, Value} ->
  	   put(Key, Value),
  	   From!{self(), ok},
  	   loop();
  	{From, stop} ->  
  	   From!stop;
  	_ ->
  	  error
  end.


 运行结果如下:

Erlang学习第二天_erlang