Reputation: 63
What am I doing wrong below? The code pegs CPU at 100% and does not end. Seems to be an infinite loop. Help appreciated.
#include <stdio.h>
int main(void)
{
unsigned long number2;
unsigned long number = 1;
#pragma omp parallel for
for (number = 1; number <= 10000; number++)
{
unsigned long max = 0, count = 0;
number2 = number;
while (number2 != 1)
{
if (number2 > max)
max = number2;
if (number2 % 2 == 0)
number2 /= 2;
else
number2 = 3 * number2 + 1;
count++;
}
}
}
Update: The following works.
Not sure what the root cause was. It could've been
#include <omp.h>
int main(int argc, char **argv)
{
unsigned int i;
#pragma omp parallel for
for (i = 1; i < 10000000; i++)
{
unsigned int number2 = i; unsigned int max; unsigned int count = 0;
while (number2 != 1)
{
if (number2 > max)
max = number2;
if (number2 % 2 == 0)
number2 /= 2;
else
number2 = 3 * number2 + 1;
count++;
}
}
}```
Upvotes: 0
Views: 134
Reputation: 2818
In the first version of your code number2
is shared, all threads access/modify it simultaneously. It is a data race ---> undefined behavior.
Upvotes: 2
Reputation: 63
Resolved.
Not sure what the root cause was. It could've been
data type was overflowing its boundaries, i.e. int -> unsigned int
or number2 had to be made private, etc.
Upvotes: 0