通过结构来PTHREAD作为参数 [英] passing struct to pthread as an argument

查看:101
本文介绍了通过结构来PTHREAD作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想通过结构通过对数字来在pthread_create 功能 pthread的。但我通过我得到当函数被调用的人数和数量是不同的,随机

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

下面是结构

struct Pairs {
    long i,j;
};

和内部主

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);
}

和功能比较

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

我是通过了结构错了?

推荐答案

这是因为你传递相同的指针所有的pthreads。

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

当你调用在pthread_create(...,(无效*)对)您传递的指针新的线程,但在接下来的迭代中要覆盖的内存(潜在的新线程之前提取了这些值)。

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;
}

这篇关于通过结构来PTHREAD作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆