Reputation: 203
I tried to parallelize Sieve of Eratosthenes algoritm using OpenMP library.
My code:
#pragma omp parallel for num_threads(4)
for (uint p = 2; (p * p) <= n; ++p)
{
if (prime[p] == true)
{
for (uint i = p * p; i <= n; i += p)
prime[i] = false;
}
}
When I try to compile, I get error message:
condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'p'
How to resolve this issue?
Upvotes: 0
Views: 173
Reputation: 32742
OpenMP has restrictions on the condition in a for
loop. The condition must be of the form p relop var
or var relop p
. Expressions using p
are not allowed. (There are also restrictions on what var
can be.)
In your case, you'll need to utilize the square root (p <= sqrt(n)
) in your condition. However, this sqrt
call needs to be made ahead of time and saved in another local variable (declared before the #pragma omp
directive).
uint sqrtn = uint(sqrt(n));
#pragma omp parallel for num_threads(4)
for (uint p = 2; p <= sqrtn; ++p)
With these restrictions on the condition, the OpenMP system can calculate how many times the loop will execute before entering it. This allows the work to be distributed appropriately.
Upvotes: 2