Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang Gen_call vs Gen_cast

Erlang OTP said gen_server:call is synchronous and gen_server:cast is asynchronous.

after testing, I find gen_server:call is synchronous . However, gen_server:cast will send message to the mailbox, but did not run tasks in parallel.

how can I create multi processes to run?

-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}.

running the code

[example_gen:add_bycall(K, K) ||  K <-  lists:seq(1, 10) ].

[example_gen:add_bycast(K, K) ||  K <-  lists:seq(1, 10) ].
like image 400
user3644708 Avatar asked Jul 21 '16 16:07

user3644708


1 Answers

Terms synchronous and asynchronous are orthogonal to terms serial and parallel. gen_server:call/2,3 is synchronous with the caller and gen_server:cast/2 is asynchronous with the caller. The work performed by one gen_server is always serial because it is performed by one process.

What terms asynchronous and synchronous means in this case. If you have code

gen_server:call(S, foo),
bar(),

Work triggered by foo is always performed before bar/0 and bar/0 is always performed after work foo is finished. Thus foo and bar/0 are synchronous. If you have code

gen_server:cast(S, foo),
bar(),

Work triggered by foo can be performed before bar/0 as well as after or even in parallel on SMP systems. Thus foo and bar/0 are asynchronous. The synchronization matters between caller and callee.

like image 142
Hynek -Pichi- Vychodil Avatar answered Nov 09 '22 13:11

Hynek -Pichi- Vychodil