Skip to content

Instantly share code, notes, and snippets.

@apauley
Created March 14, 2013 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save apauley/5164716 to your computer and use it in GitHub Desktop.
Save apauley/5164716 to your computer and use it in GitHub Desktop.
-module(sleepsort).
-export([test/0,
sort/1]).
test() ->
[1,2,3] = sort([1,2,3]),
[1,2,3] = sort([2,1,3]),
[] = sort([]),
[2,4,8,12,19] = sort([19,8,4,12,2]),
Seq100 = lists:seq(1,100),
Seq100 = sort(lists:reverse(Seq100)),
ok.
sort(List) ->
F = fun(Int) ->
Self = self(),
spawn(fun() -> sleepsend(Self, Int) end)
end,
lists:foreach(F, List),
receive_sort(List, []).
receive_sort([], Sorted) ->
lists:reverse(Sorted);
receive_sort([_H|T], Acc) ->
receive
{elem, Int} ->
receive_sort(T, [Int|Acc])
after 60000 ->
{error, timeout}
end.
sleepsend(From, Int) when is_integer(Int) ->
timer:sleep(Int),
From ! {elem, Int},
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment