Green Threads: A Classic Example

Submitted by Chandon on Fri, 07/23/2010 - 04:18

Now that I have green threads basically working with the API functionality I discussed in my last blog post, I've been working on coming up with tests/examples that clearly demonstrate both how green threads in Parrot work and that they work as advertised. With that goal in mind, this blog post is about a classic concurrent programming example: The Sieve of Eratosthenes.

This example was apparently initially suggested by Doug McIlroy. After screwing this up the first few tries from memory, I cheated and googled it. I found a good diagram here: http://swtch.com/~rsc/thread/

The Sieve of Eratosthenes finds prime numbers using simple recursive concept. Start with the first prime number, 2, and count up. For any given number, if it isn't divisible by any of the prime numbers below it then it must be a prime.

This can be implemented with communicating processes by setting up a chain of processes, one for each prime number. Starting with two and counting up, pass each number down the chain. If it's divisible by any number in the chain it's not prime and can be thrown away. If it gets to the end of the chain, it's prime and it gets to be the new end of the chain.

Below is the PIR code, using the Task API that I described in my last blog post.