使用 c++ 中的线程进行 shell 排序

Shell sort using threads in c++

本文关键字:shell 排序 线程 c++ 使用      更新时间:2023-10-16

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

我需要将初始整数数组分成 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");
}

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