I have these two functions:
Code:
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:
Code:
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?