For school I have a multi-threaded assignment. Each thread is supposed to take a number from the console input, find all of its prime numbers, and return all those prime numbers as an array. I'm struggling with returning the array in such a way that I can display it. Here is some of my code:
int *number;
for (int i =1; i < argc; i++) {
pthread_create(&thread[i], NULL, prime_nums, (void*)argv[i]);
}
for (int i =1; i < argc; i++) {
pthread_join(thread[i],(void**) &number);
printf("%d\n", *(number + 0)); //This is just to test if the variable is correct
}
...
void *prime_nums(void*m) {
int n = atoi(m);
int count = 0;
int f = 2;
int primeNumbers[MAX_PRIME];
/*printf("%d: ", n);*/
while (n > 1 && count < MAX_PRIME) {
if (n % f == 0) {
primeNumbers[count++] = f;
n /= f;
}
else {
f += 1;
}
}
/*printf("\n");*/
int test[2];
test[0] = 0;
test[1] = 1;
test[2] = 2;
pthread_exit(test);
}
I've already checked the array primeNumbers
in my thread and the data within the array is correct, but I can't figure out how to save that array to another array in my main function.
The array test
in your thread function is a local variable that goes out of scope when the function returns (and the thread exits). Returning the address of a local variable and subsequently dereferencing that address invokes undefined behavior.
You need to dynamically allocate memory for the array and return that pointer:
void *prime_nums(void*m) {
...
int *test = malloc(sizeof(int) * 3);
test[0] = 0;
test[1] = 1;
test[2] = 2;
pthread_exit(test);
}
Also, the second parameter to pthread_exit
should be the address of a void *
:
void *rval;
int *number
pthread_join(thread[i], &rval);
number = rval;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With