Jos Jos - 4 months ago 42
C Question

passing struct to pthread as an argument

Ok I am trying to pass pair of numbers through

struct
to
pthread_create
function in
pthread
. But the numbers i am passing and numbers i am getting when the function is called are different and random

Here is the
struct


struct Pairs {
long i,j;
};


And inside main

void main()
{
long thread_cmp_count = (long)n*(n-1)/2;
long t,index = 0;
struct Pairs *pair;
pair = malloc(sizeof(struct Pairs));

cmp_thread = malloc(thread_cmp_count*sizeof(pthread_t));
for(thread = 0;(thread < thread_cmp_count); thread++){
for(t = thread+1; t < n; t++){
(*pair).i = thread;
(*pair).j = t;
pthread_create(&cmp_thread[index++], NULL, Compare, (void*) pair);

}
}

for(thread= 0;(thread<thread_cmp_count); thread++){
pthread_join(cmp_thread[thread], NULL);
}

free(cmp_thread);
}


And function Compare

void* Compare(void* pair){
struct Pairs *my_pair = (struct Pairs*)pair;
printf("\nThread %ld, %ld", (*my_pair).i, (*my_pair).j);
return NULL;
}


Number I am getting and it is also random.

Thread 0,2
Thread 1,2
Thread 2,3
Thread 2,3
Thread 2,3
Thread 2,3


am i passing the
struct
wrong ?

Answer

That is because you are passing the same pointer to all pthreads.

When you invoke pthread_create(..., (void*) pair) you are passing the pointer to the new thread, but in the next iteration you are overwriting that memory (potentially before the new thread has extracted those values).

    long thread_cmp_count = (long)n*(n-1)/2;
    long t,index = 0;
    struct Pairs *pair;

    cmp_thread = malloc(thread_cmp_count*sizeof(pthread_t));
    for(thread = 0;(thread < thread_cmp_count); thread++){
        for(t = thread+1; t < n; t++){
            // allocate a separate pair for each thread
            pair = malloc(sizeof(struct Pairs));
            (*pair).i = thread;
            (*pair).j = t;
            pthread_create(&cmp_thread[index++], NULL, Compare, (void*) pair);

        }
    }

    for(thread= 0;(thread<thread_cmp_count); thread++){
        pthread_join(cmp_thread[thread], NULL);
    }

    free(cmp_thread);

.

void* Compare(void* pair){
    struct Pairs *my_pair = (struct Pairs*)pair;
    printf("\nThread %ld, %ld", (*my_pair).i, (*my_pair).j);

    // free that memory after it has been used
    free (pair);
    return NULL;
}
Comments