将struct作为参数传递给pthread

时间:2013-11-25 14:55:31

标签: c multithreading struct pthreads

好的我正试图通过struct中的pthread_createpthread函数传递一对数字。但是我传递的数字和调用函数时得到的数字是不同的随机

以下是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("\nThread %ld, %ld", (*my_pair).i, (*my_pair).j);
    return NULL;
}

我得到的号码,也是随机的。

Thread 0,2
Thread 1,2
Thread 2,3
Thread 2,3
Thread 2,3
Thread 2,3
我正在传递struct错误吗?

2 个答案:

答案 0 :(得分:18)

那是因为你将相同的指针传递给所有pthreads。

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

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

答案 1 :(得分:3)

问题解决了。问题是重叠。使用指针作为类型array的{​​{1}}对,它已被解决

这是正确的代码

struct

功能比较

long thread_cmp_count = (long)n*(n-1)/2;
long t,index = 0;
Pair * pair;
pair = malloc(thread_cmp_count*sizeof(Pair));

free(thread_handles);

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

free(thread_handles);