Skip to content

Instantly share code, notes, and snippets.

@chiroptical
Created June 24, 2023 21:01
Show Gist options
  • Save chiroptical/3b04d18a596529568c7f60dc853cfc5a to your computer and use it in GitHub Desktop.
Save chiroptical/3b04d18a596529568c7f60dc853cfc5a to your computer and use it in GitHub Desktop.
Checking order of operations for async call within sync call
-module(check_order).
-behaviour(gen_server).
-export([
start_link/0,
thing/1,
init/1,
handle_call/3,
handle_cast/2
]).
-record(state, {text :: string()}).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
thing(Pid) ->
gen_server:call(Pid, thing).
async_thing(Pid) ->
gen_server:cast(Pid, async_thing).
init(_Args) ->
{ok, #state{text = "init"}}.
handle_call(thing, _From, _State = #state{text = CurrentText}) ->
io:format("Starting async thing...~n"),
async_thing(self()),
io:format("Sleep 1 second...~n"),
ok = timer:sleep(1000),
{reply, {thing, CurrentText}, #state{text = "async_thing"}}.
handle_cast(async_thing, State = #state{text = CurrentText}) ->
io:format("Async thing says ~p...~n", [CurrentText]),
{noreply, State}.
rebar3 shell
===> Verifying dependencies...
===> Analyzing applications...
===> Compiling reminder
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit]
Eshell V13.2.2 (abort with ^G)
1> {ok, Pid} = check_order:start_link().
{ok,<0.162.0>}
2> check_order:thing(Pid).
Starting async thing...
Sleep 1 second...
Async thing says "async_thing"...
{thing,"init"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment