I need some help with this. I am making a threaded factor program. Takes arguments from the command line, finds the prime factors and outputs them.
However, my problem is that if I have multiple arguments being passed in (e.x. 20 15 10 5), all of my outputs use the same values as the first argument being passed in.
example output:
20: 2 2 5
15: 2 2 5
10: 2 2 5
5: 2 2 5
Could any of you get a second pair of eyes on this and see why I am printing the same thing for different threads?
My intuition says that it is because I am using one static array in my struct, and each time a new thread uses it, it overwrites data already there from previous calculations. I could be wrong.
struct prime_struct {
int array[100];
int limit;
};
void* prime_factor(void* number)
{
int i, count = 0; // count is used to increment through array
int n = *((int*)number);
int limit = *((int*)number);
struct prime_struct *arg_struct = (struct prime_struct*) number;
while (n % 2 == 0)
{
n = n / 2; // Halve number
arg_struct->array[count] = 2; // Two is a factor store it in position 1 of array
count++;
}
for (i = 3; i <= limit; i = i + 2)
{
while(n % i == 0)
{
n = n / i;
arg_struct->array[count] = i;
count++;
}
}
arg_struct->limit = count;
pthread_exit(0);
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("Please enter an integer value.");
exit(-1);
}
int i, j, k, m;
int args = argc - 1;
int number[args];
pthread_t tids[args]; // pthread_t tid; // Thread id
// struct prime_struct array_struct[args];
struct prime_struct *array_struct = (struct prime_struct*) number;
for (i = 0; i < args; i++)
{
number[i] = atoi(argv[i + 1]);
pthread_attr_t attr; // Create attributes
pthread_attr_init(&attr);
pthread_create(&tids[i], &attr, prime_factor, &number[i]);// &array_struct[i + 1]); // plus one because I want the first number not the ./assn3
}
for (j = 0; j < args; j++)
{
// Wait until thread is done, get value back from child and print factors
pthread_join(tids[j], NULL);
}
int limit = array_struct->limit;
for (k = 0; k < args; k++) // print array
{
printf("%s: ", argv[k + 1]);
for (m = 0; m < limit; m++)
{
printf("%d ", array_struct->array[m]);
}
printf("\n");
}
return 0;
}
Example output for an input of 20 would be
20: 2 2 5