c++multithreadingsortingshellsort

Shell sort using threads in c++


I'm trying to implement parallel shell sort using thread library.

I need to divide initial array of ints into thN parts, sort them in thN threads and finally merge them together. The code below is without merge part because at first i wanna to find out the reason sort in threads doesn't work properly (there aren't any warnings or mistakes, ints just stay unsorted).

I checked thread work in simple examples and everything was ok.

So could anyone tell me what am I doing wrong?

#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");
}

Solution

  • It's answered here Difference between pointer and reference as thread parameter. Thread deduces argument types and stores them by value. That's why references won't work and you should use pointer.