Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

c - 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("
Thread %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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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("
Thread %ld, %ld", (*my_pair).i, (*my_pair).j);


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...