Skip to content

Instantly share code, notes, and snippets.

@peixian
Last active August 1, 2024 16:10
Show Gist options
  • Select an option

  • Save peixian/83e9edff9a7e8de50c4c6d3a82eb4094 to your computer and use it in GitHub Desktop.

Select an option

Save peixian/83e9edff9a7e8de50c4c6d3a82eb4094 to your computer and use it in GitHub Desktop.
% Assume the existence of process `process_b`, which may be overloaded. We're in `process_a` right now.
% two ways to handle it:
% do not actually cancel, just disregard the message from B when it comes back.
% This is for circumstances where the extra computation is fine
Pid1 = spawn(fun () -> gen_server:call(process_b, func_name, {Args}, 5000)) % waits for 5 seconds before exiting with a `timeout`
Pid2 = spawn(fun () -> gen_server:call(process_b, func_name, {Args}, 5000)) % waits for 5 seconds before exiting with a timeout
link(Pid1, Pid2) % links the two pids, when one comes back and dies, the other one is also killed.
% do actually cancel whichever one was previously running when one comes back
% we trap the exit signal, when we are asked to kill we make sure to cancel
% the call to B so it doesn't do extra work
% need a special actor instead of just a func
-module(actor_that_traps_exit)
start() ->
process_flag(trap_exit, true),
gen_server:call(process_b, func_name, {Args}, 5000).
handle_info('EXIT', Pid, Reason) ->
gen_server:call(process_b, cancel_func_name, {}),
% OR just kill the other process:
gen_server:call(process_b, exit, {}),
exit().
% ..... back in process A
Pid1 = spawn(actor_that_traps_exit:start)
Pid2 = spawn(actor_that_traps_exit:start)
link(Pid1, Pid2)
% in elixir land we can also use Task.async, which is a spawn that lets you await
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment