Trouble with pthread_create and pthread_join [Archive] - C Board

PDA

View Full Version : Trouble with pthread_create and pthread_join


Yasir_Malik
10-02-2003, 11:45 AM
I have these two functions:
void make_threads(pthread_t *threads, int num_threads, void* (*func)(void *))
{
int i, *id;

if((threads = (pthread_t *) calloc(num_threads, sizeof(pthread_t))) == NULL)
{
perror("make_threads calloc");
exit(0);
}

for(i = 0; i < num_threads; i++)
{
if((id = (int *) calloc(1, sizeof(int))) == NULL)
{
perror("make_threads id calloc");
exit(0);
}

*id = i; // pointer needed because if I just passed address of i
// all threads would have the same id address, hence
// same id

if(pthread_create(&threads[i], NULL, func, (void *) id) != 0)
{
perror("make_threads pthread_create");
exit(0);
}
}
}

void join_threads(pthread_t *threads, int num_threads)
{
int i, *ret_val;

if((ret_val = (int *) calloc(num_threads, sizeof(int))) == NULL)
{
perror("join_threads calloc");
exit(0);
}

printf("before loop in join_threads\n");
for(i = 0; i < num_threads; i++)
if(pthread_join(threads[i], (void **) (&(ret_val))) != 0)
{
perror("join_threads pthread_join");
exit(0);
}
printf("out of join_threads\n");

}

and I call them as follows:
pthread_t *producers, *qsort_consumers, *bsort_consumers;

make_threads(producers, num_producers, &producer);
make_threads(qsort_consumers, num_consumers, &qsort_consumer);
make_threads(bsort_consumers, num_consumers, &bsort_consumer);
printf("hello 1\n");
join_threads(producers, num_producers);
printf("hello 2\n");
join_threads(qsort_consumers, num_consumers);
join_threads(bsort_consumers, num_consumers);
printf("hello 2\n");


The problem is that the program always dumps core and never prints "hello 2" or "hello 3". It also only prints "before loop in join_threads" only once and never prints "out of join_threads". What's wrong my join_threads function?

Salem
10-02-2003, 12:58 PM
> make_threads(producers, num_producers, &producer);
This does not allow you to return the modified pointer, as modified by the function.

You need to call it as
producers = make_threads(num_producers, &producer);

or
make_threads(&producers, num_producers, &producer);

With appropriate modifications to the function of course

Yasir_Malik
10-02-2003, 01:48 PM
Thanks, that's what I was just about thinking about doing.