好吧我试图通过struct
到pthread_create
函数在pthread
中传递一对数字。但我通过我得到当函数被调用的数量和数量是不同的,随机将struct传递给pthread作为参数
这里是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;
}
我得到的数字,它也是rando米
Thread 0,2
Thread 1,2
Thread 2,3
Thread 2,3
Thread 2,3
Thread 2,3
我是否通过了struct
错误?
请注意,在C,结构访问通过指针被永远不会写成'(* foo).bar':而是使用'foo-> bar'。 – unwind