lehast22 lehast22 - 11 months ago 43
C Question

Print multiple child's return value after joining multiple threads

What my program is essentially supposed to do is that it takes multiple command line arguments and creates a thread for each of them. Each thread is assigned to a primeFactors function that returns a pointer to the values of the primefactors.

void *primeFactors(void *param)
int* p_a = malloc((1000) * sizeof p_a[0]); //arbitrary size, will scale better later
int number = atoi(param);
..... prime factor part .......
p_a[j] = 0; //sentinel value

I've checked and this does, in fact, return a pointer that points to all the right prime factors. My main function looks like this

int main(int argc, char *argv[])
int count = 2; //arbitrary 2 just for the purpose of testing 2 arguments
pthread_t = malloc(count * sizeof(pthread_t));
pthread_attr_t attr;
int i;
for (i = 0; i < count; i++)
pthread_create(&tid[i], &attr, primeFactors, argv[i+1]);
int j;
void *prime_array;
int *p;
for (j = 0; j < count; j++)
pthread_join(tid[i], &prime_array);
p = prime_array;
int n = 0;
while (p[n] != 0)
printf("%d ", p[n]);
return 0;

I've checked this program with only a single command line argument and without the for loop around the pthread_join code and the program works. The problem seems to arise when I join multiple threads and print the return value array of each thread. When I run through it with two command line arguments like I have been I get a huge list of numbers as if I ran a random number generator instead of finding prime factors. I think the error might be something small so I'd appreciate any suggestions you may have!

Answer Source

Since you haven't posted the full code it is not possible to pinpoint the exact problem(s) causing you grief, however here goes -

Obvious error -

  1. pthread_join(tid[i], &prime_array); should be
    pthread_join(tid[j], &prime_array); /* Jay instead of Eye. */

Suggestions -

  1. Instead of for (i = 0; i < count; i++)
    use for (i = 0; i < (argc - 1); i++) /* Use 'argc' instead of the arbitrary 'count' */.
    Or, set int count = argc - 1.

  2. Check return value of functions used (malloc, pthread_xxx()).
    Had you done that you would have probably noticed that pthread_join() returned an error value.