-module(kvs).
-export([start/0,store/2,lookup/1,test/0]).
start() -> register(kvs, Pid=spawn(fun() -> loop() end)),
io:format("Pid = ~p~n",[Pid]).
test() ->
receive
{kvs, Reply} ->
Reply
end.
store(Key,Value) -> rpc({store,Key,Value}).
lookup(Key) -> rpc({lookup,Key}).
receive
{kvs,Reply} ->
Reply
end.
io:format("P1 = ~p~n",[P1]),
receive
{From, {store,Key,Value}}->
P= self(),
io:format("P = ~p~n",[P]),
io:format("From = ~p~n",[From]),
put(Key, {ok, Value}),
From ! {kvs, true},
loop();
{From, {lookup,Key}} ->
io:format("From = ~p~n",[From]),
From ! {kvs,get(Key)},
loop()
end.
-export([start/0,store/2,lookup/1,test/0]).
start() -> register(kvs, Pid=spawn(fun() -> loop() end)),
io:format("Pid = ~p~n",[Pid]).
test() ->
receive
{kvs, Reply} ->
Reply
end.
store(Key,Value) -> rpc({store,Key,Value}).
lookup(Key) -> rpc({lookup,Key}).
rpc(Q) ->
%% self() 创建的进程,该进程接收消息的语句,应该写在 self() 之后,并 在同一函数(正确) 而写在test() 里面的receive 就收不到消息了(错误的写法)
kvs ! {self(), Q},receive
{kvs,Reply} ->
Reply
end.
loop() ->
%% P1 和 P,Pid 属于同一进程,它们的值都一样,因为它们都是在Pid 进程里面创建的
P1= self(),io:format("P1 = ~p~n",[P1]),
receive
{From, {store,Key,Value}}->
P= self(),
io:format("P = ~p~n",[P]),
io:format("From = ~p~n",[From]),
put(Key, {ok, Value}),
From ! {kvs, true},
loop();
{From, {lookup,Key}} ->
io:format("From = ~p~n",[From]),
From ! {kvs,get(Key)},
loop()
end.