Skip to content

Instantly share code, notes, and snippets.

@elisehuard
Created October 17, 2010 16:20
Show Gist options
  • Save elisehuard/630980 to your computer and use it in GitHub Desktop.
Save elisehuard/630980 to your computer and use it in GitHub Desktop.
concurrent sieve of erathostenes - analogy with go example
-module(sieve).
-export([run/1]).
run(M) ->
Numbers = lists:seq(3, M),
Startpid = self(),
spawn_link(fun() -> prime_filter(Startpid, 2, Numbers) end),
gather().
gather() ->
receive
%% concatenate received primes
{Prime, finish} ->
[Prime];
{Number} ->
[Number|gather()]
end.
prime_filter(StartPid, Prime, []) ->
StartPid ! {Prime, finish};
prime_filter(StartPid, Prime, List) ->
Indivisible = lists:filter(fun(Elem) -> (Elem rem Prime) /= 0 end, List),
[NextPrime|Rest] = Indivisible,
StartPid ! {Prime},
spawn(fun() -> prime_filter(StartPid, NextPrime, Rest) end).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment