Skip to content

Instantly share code, notes, and snippets.

@Rembane
Created May 13, 2015 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rembane/1a95c957031e1a7935d1 to your computer and use it in GitHub Desktop.
Save Rembane/1a95c957031e1a7935d1 to your computer and use it in GitHub Desktop.
How to get messages in correct order, with interference.
-module(msgorder).
-compile(export_all).
% How to get messages in correct order, even though things outside of our
% control try to put them in a semi-random order.
f(T, X) ->
Parent = self(),
Ref = make_ref(),
spawn_link(fun() -> timer:send_after(T, Parent, {Ref, {T, X}}) end),
receive {Ref, Y} -> Y end.
test() ->
lists:map(fun (X) -> f(random:uniform(10)*100, X) end, lists:seq(1,10)).
@elbrujohalcon
Copy link

why spawn_link and timer:send_after? You could've just done:

f(T, X) ->
    erlang:send_after(T, self(), {Ref, {T, X}}),
    receive {Ref, Y} -> Y end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment