将 struct 作为参数传递给 pthread [英] passing struct to pthread as an argument

查看:39
本文介绍了将 struct 作为参数传递给 pthread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在尝试通过 struct 将一对数字传递给 pthread 中的 pthread_create 函数.但是我传递的数字和调用函数时得到的数字是不同且随机的

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

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("
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

我传递的 struct 错了吗?

推荐答案

那是因为您将相同的指针传递给所有 pthread.

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

当您调用 pthread_create(..., (void*) pair) 时,您将指针传递给新线程,但在下一次迭代中,您将覆盖该内存(可能在新线程之前)线程已经提取了这些值).

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

这篇关于将 struct 作为参数传递给 pthread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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