Created
October 17, 2010 16:20
-
-
Save elisehuard/630980 to your computer and use it in GitHub Desktop.
concurrent sieve of erathostenes - analogy with go example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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