0
我正在嘗試使用線程庫實現並行shell排序。使用C++中的線程進行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");
}
1.你應該在'main()'中爲你的線程向量使用'std :: vector'和'emplace_back'。 2.線程構造調用中的'wp'參數應該是引用包裝的'std :: ref(wp)'。例如:參數應該是'shellSort,std :: ref(wp),i' –
WhozCraig
@WhozCraig,哦,謝謝!我以前看到過,但完全忘了這個..現在沒關係! – Chet