繁体   English   中英

使用线程对数组的两半进行排序,但是仅对后半部分进行排序

[英]Using threads to sort two halves of an array, but only second half is being sorted

我编写了一个快速程序来对一个数组的两半进行排序,当我测试排序对一个数组的效果很好时,但是当我将数组分为两部分并将一半传递给每个线程进行排序时,我完成了打印数组,只有后半部分看起来已排序。 我究竟做错了什么? 以下是我的排序功能和主要内容。

void *sort(void *object){

  struct array_struct *structure;
  structure = (struct array_struct *) object;

  int *array = structure->partition;
  int size = structure->size;
  qsort(array, size, sizeof(int), cmpfunc);

  printf("Sorted %d elements.\n", size);
}

这是我的主要工作,假设所有包含都很好,编译也还不错,这不是我的所有代码,而只是与我的问题有关的部分。

int main(int argc, char const *argv[]){


int segments = 2;
pthread_t threads[segments];

int i, *numbers; //iterator i, and pointer to int array 'numbers'
numbers = randomArray(); //return an array of size 50 filled with random ints



for(i = 0; i < segments; i++){
    struct array_struct array;//struct to pass as argument on thread creation

        int *partition = numbers + (i * (50/segments));//obtain the first index of partition
        array.partition = partition; //when i = 0 partition is 0 through 24, when i = 1 partition is 25 through 49 
        array.size = 50/segments; //25
        pthread_create(&threads[i], NULL, sort, (void *) &array);

}

for(i = 0; i < segments; i++){
    pthread_join(threads[i], NULL);
}

for(i = 0; i < 50; i++){
    printf("%d\n", numbers[i]);
}

pthread_exit(NULL);
}

这是我的输出,如果有帮助的话:

Sorted 25 elements.
Sorted 25 elements.

19 16 14 16 20 6 17 13 8 39 18 0 26 46 45 17 7 46 45 29 15 38 43 19 17 0 2 4 7 12 12 12 14 14 16 17 20 22 22 23 26 29 30 32 33 37 38 38 43 43 46

您正在将参数传递给第一个线程array ,然后立即用第二个线程的参数覆盖该结构的内容。 因此,两个线程都将看到第二个线程的参数。

您应该做的是有两个单独的参数。 例如,使array为2个结构的数组,并将&array[0]传递给第一个线程,并将&array[1]传递给第二个线程。

同样,在for循环范围内声明array也很危险。 一旦for循环结束,该变量将超出范围,您的线程可能会读入无效变量。 您应该在函数级别声明array ,以便线程可以访问它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM