C - 使用结构与 pthread 合并排序



我正在尝试对存储在每个给定段中的数组中的一些数字进行排序。

typedef struct _sortee{
    int * nums;//array of numbers to be sorted
    size_t num_elems;//# of elements in each segment
    size_t segment_count;//# of segments
    int **ptrs;//pointers to the array of numbers
    int index;
}sortee;

问题是每次创建线程时,sortlist->index 中的数字都会更改,因此有时不会对正确的段进行排序。我知道要解决这个问题,我必须传入我创建的结构数组作为pthread_create的第 4 个参数,但我无法想出一个想法,因为该结构也有要排序的数组。

pthread_t tid[sortlist->segment_count];
for(i=0; i<(int)sortlist->segment_count; i++){
    sortlist->index = i;
    pthread_create(&tid[i], NULL, sort, sortlist);
}

for(i=0; i<(int)sortlist->segment_count; i++){
    sortlist->index = i;
    pthread_join(tid[i], NULL);
}

这是排序算法的第一部分。运行这个后,我有另一个合并函数来对其余部分进行排序。

void *sort(void *ptr) {
sortee *sortlist = (sortee *)ptr;
qsort(sortlist->ptrs[sortlist->index], sortlist->num_elems, sizeof(int), comp);
fprintf(stderr, "Sorted %d elements.n", (int)sortlist->num_elems); 
return sortlist;
}

有人可以给我一点想法吗?谢谢!对不起,如果我的英语很难理解...

就像你有一个数组,所以每个pthread都有自己的tid,有另一个数组,这样每个pthread都可以有自己的索引:你可以将不同的结构传递给每个pthread,它存储了该pthread的索引以及指向它们共享的结构的指针。

最新更新