3
Erlang OTP表示gen_server:call
是同步的,而gen_server:cast
是異步的。Erlang Gen_call vs Gen_cast
經過測試,我發現gen_server:call
是同步的。 但是,gen_server:cast
會將郵件發送到郵箱,但不是並行運行任務。
我該如何創建多進程來運行?
-module(example_gen).
-behaviour(gen_server).
-export([start_link/0]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-export([
add_bycall/2,
add_bycast/2
]).
-define(SERVER, ?MODULE).
-record(state, {}).
add_bycall(Key, Value) ->
gen_server:call(?SERVER, {bycall, Key, Value}).
add_bycast(Key, Value) ->
gen_server:cast(?SERVER, {bycast, Key, Value}).
example(Key, Value) ->
timer:sleep(2000),
io:format("finished [~p, ~p] at [~p] ~n", [Key, Value, erlang:system_time(milli_seconds)]).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
init([]) ->
{ok, #state{}}.
handle_call({bycall, Key, Value}, _From, State) ->
example(Key, Value),
{reply, ok, State};
handle_call(_Request, _From, State) ->
{reply, ok, State}.
handle_cast({bycast, Key, Value}, State) ->
example(Key, Value),
{noreply, State};
handle_cast(_Request, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
運行代碼
[example_gen:add_bycall(K, K) || K <- lists:seq(1, 10) ].
[example_gen:add_bycast(K, K) || K <- lists:seq(1, 10) ].
謝謝。它解釋了很多。 – user3644708