Question

I don't know what am I doing wrong in the following function. I am trying to return an array but it Seg Faults at while loop in the compute_average. I am using a structure to initialize the begin and the last word and used in the function "compute_average" You can assume the compute_average function works fine which was already there but I changed the code when using the structure or "first" and "second" value.

typedef struct parallel{
unsigned long first, second;
}Parallel;

return final_array;

}

Était-ce utile?

La solution

Your argument to pthread_join is wrong. You are, in effect, doing this:

pthread_join(tid, NULL);

You need to supply the address of a void * variable (and technically you should capture the return value of pthread_join itself, in case it fails, although here it won't):

error = pthread_join(tid, &ary1);

If error==0 after this, ary1 will contain the value returned from the thread, and array1 = ary1 will suffice to make it useful (no cast is needed there).

(As ldav1s noted, the size is wrong too. You may want to augment the code to return more than just one pointer. Or you could fill in a data structure supplied by the thread's caller. [I'm making various guesses here about how you might implement multiple threads, in the end. The guesses may be wrong. :-) ])

Autres conseils

This:

unsigned long *array1;
...
size = (sizeof(array1)/sizeof(array1[0]));

Looks extremely suspicious, unless size is supposed to be 1 or 2. array1 is a pointer, not an array.

pthread_join(tid, ary1);

should be:

pthread_join(tid, &ary1);

If you want to get any data back from compute_prime at all. You also need to "tack on" some kind of size in the data returned from compute_prime to tell you how many elements you've got.

You're also leaking memory allocated in compute_prime, better free(ary1).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top