《Erlang程序設計》第十章kvs的例子函數
-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.
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更易讀,易懂oop
注意測試
defp
定義Process
模塊:name
測試:spa
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)>