I'm working on understanding threads and have run up against this segmentation fault that I can't seem to correct. I have narrowed down the error to the pthread_join()
function, but can't seem to go any further. My understanding is that the for loop needs to be the same as the one for the pthread_create()
and that the variable that is passed in is the dereferenced pointer being passed into the pthread_exit()
function. Any direction would be greatly appreciated.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//void *runner(void *param);
void *pFactor(void *param)
{
int *pFArray = malloc(sizeof(int) *32);
int myNum = atoi(param);
int count = 0;
printf("I'm getting here");
while (myNum % 2 == 0)
{
pFArray[count] = 2;
myNum = myNum/2;
count++;
}
for (int i = 3; i < sqrt(myNum); i += 2)
{
while (myNum % i == 0)
{
pFArray[count] = i;
myNum = myNum/i;
count++;
}
}
if (myNum > 2)
{
pFArray[count] = myNum;
}
//int *arrPtr = (int*) malloc(10);
//arrPtr = pFArray;
//return (void *) arrPtr;
//return fprint("I made it to the end of the pFactor function")
pthread_exit(pFArray);
}
int main(int argc, char *argv[])
{
pthread_t tid[argc];
pthread_attr_t attr;
if (argc == 0)
{
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
}
if (argc < 0)
{
fprintf(stderr, "%d must be >= 0\n", atoi(argv[1]));
return -1;
}
/* Get the default attributes */
pthread_attr_init(&attr);
/* Create the thread */
for (int i = 1; i < argc; i++)
{
tid[i] = i;
pthread_create(&tid[i], &attr, pFactor, &argv[i]);
printf("still working\n");
}
printf("still working\n");
/* Wait for the thread to exit */
for (int i = 1; i < argc; i++)
{
tid[i] = i;
void *my_Ptr;
printf("still working 1\n");
pthread_join(tid[i], &my_Ptr);
printf("still working 2\n");
for (;;)
{
printf("%d", atoi(argv[i]));
printf(": %d",((int*) my_Ptr)[i-1]);
}
//printf("%d", atoi(argv[i]));
//printf(": %d",((int*) my_Ptr)[i-1]);
} /*This is where you want to pass in the sum variable*/
}
tid[i]
? In either loop?pthread_create()
fills in the appropriate value, and those are the values you must later pass topthread_join()
. – John Bollinger