I would like to create a simple parallel Sieve of Erastosthenes Java program, that would be at least a bit more effective then a serial version I’ve posted below.
public void runEratosthenesSieve(int upperBound) {
int upperBoundSquareRoot = (int) Math.sqrt(upperBound);
boolean[] isComposite = new boolean[upperBound + 1];
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) {
System.out.print(m + " ");
int threads=4;
for (int n=1; n<=threads; n++) {
int job;
if (n==1) {job = m * m;} else {job = (n-1)*upperBound/threads;}
int upToJob = n*upperBound/threads;
for (int k = job; k <= upToJob; k += m)
{
isComposite[k] = true;
}
}
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++)
if (!isComposite[m])
System.out.print(m + " ");
}
I have created a loop for dividing work for 4 threads. Though I don’t know how to make actual thread code from it. How to send variables and start 4 threads with part of job for each.
I can propose following solution: there are 4 workers thread and 1 master thread. Worker threads get jobs from queue. Job is basically 3 numbers: from, to, step. Master mean while must wait until all threads a done. When they’re done it searches for next prime number and create 4 jobs. Synchronization between master and workers can be achieved using Semaphore: master tries to acquire 4 permits while every worker releases 1 permit when it’s done.