《Erlang程序设计》第十章kvs的例子
Erlang实现:
-module(kvs).
-export([start/0, store/2, lookup/1]).
start() -> register(kvs, spawn(fun() -> loop() end)).
store(Key, Value) -> rpc({store, Key, Value}).
lookup(Key) -> rpc({lookup, Key}).
rpc(Q) ->
kvs ! {self(), Q},
receive
{kvs, Reply} ->
Reply
end.
loop() ->
receive
{From, {store, Key, Value}} ->
put(Key, {ok, Value}),
From ! {kvs, true},
loop();
{From, {lookup, Key}} ->
From ! {kvs, get(Key)},
loop()
end.
Elixir实现
defmodule Kvs do
def store(key, value) do
rpc({:store, key, value})
end
def start do
Process.register spawn(fn -> loop() end), :kvs
end
def lookup(key) do
rpc({:lookup, key})
end
defp rpc(q) do
send :kvs, {self(), q}
receive do
{:kvs, reply} ->
reply
end
end
defp loop do
receive do
{form, {:store, key, value}} ->
Process.put key, value
send form, {:kvs, true}
loop()
{form, {:lookup, key}} ->
send form, {:kvs, Process.get key}
loop()
end
end
end
使用Elixir更易读,易懂
注意
- Elixir中module名要大写开头
- 不导出的函数即私有函数使用
defp
定义 - Elixir进程相关操作使用
Process
模块 - Eralng原子在Elixir形式是
:name
测试:
iex(1)> c("kvs.ex")
[Kvs]
iex(2)> Kvs.start
true
iex(3)> Kvs.store "a", 1
true
iex(4)> Kvs.lookup "a"
1
iex(5)>