0

我正在尝试使用线程库实现并行 shell 排序。

我需要将初始整数数组划分为thN部分,在thN线程中对它们进行排序,最后将它们合并在一起。下面的代码没有合并部分,因为起初我想找出线程中排序不能正常工作的原因(没有任何警告或错误,整数只是保持未排序)。

我在简单的示例中检查了线程工作,一切正常。

那么谁能告诉我我做错了什么?

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <ctime>
#include <vector>
using namespace std;

void shellSort(vector <vector<int>>& wp, int k)
 {
    int n = wp[k].size();
    for (int gap = n / 2; gap > 0; gap /= 2)
     {

       for (int i = gap; i < n; i++)
        {
           int temp = wp[k][i];
           int j;
           for (j = i; j >= gap && wp[k][j - gap] > temp; j -= gap)
               wp[k][j] = wp[k][j - gap];
           wp[k][j] = temp;
        }
      }
 }

  int main()
 {
    int N, thN, i;
    cout << "\nEnter the length of array: ";
    cin >> N;
    cout << "\nEnter the amount of threads: ";
    cin >> thN;
    int* A = new int[N];
    for (i = 0; i < N; i++)
        A[i] = rand() % 100;

    thread* t = new thread[thN];

    vector<vector<int> > wp(thN, vector<int>());

    int start = 0;
    for (i = 0; i < thN; i++){
        for (int j = start; j < start + N / thN; j++){
            wp[i].push_back(A[j]);
        }
        start += N / thN;
    }

    double endTime, startTime;
    startTime = clock();

    for (i = 0; i < thN; i++)
        t[i] = thread(shellSort,wp,i);

    for (i = 0; i < thN; i++)
        t[i].join();

    endTime = clock();

    cout << "Runtime of shell sort: " << (endTime - startTime) / 1000 << endl;// time in miliseconds
    system("pause");
}
4

1 回答 1

0

在这里回答了指针和引用作为线程参数的区别。线程推导出参数类型并按值存储它们。这就是为什么引用不起作用,你应该使用指针。

于 2017-05-10T16:11:16.033 回答