简体   繁体   中英

C++ Multithreaded mergesort not working

I am new to learning c++ and I am attempting to implement a multi-threaded version of MergeSort. I have compared my algorithms to numerous implementations online and it appears to be nearly identical, however, I am not getting the correct output. The output is even including numbers not found in the original input.

using namespace std;
int a[]  = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};  /* target array */
int arrayLen;

void merge(int low, int mid, int high)
{
    int left = low;
    int right = mid+1;

    int b[high-low+1];
    int i, cur = 0;

    while(left <= mid && right <= high) {
        if (a[left] <= a[right])
            b[cur++] = a[left++];
        else
            b[cur++] = a[right++];
    }

    while(left <= mid) b[cur++] = a[left++];
    while(right <= high) b[cur++] = a[right++];
    cur--;
    while (cur >= 0){
        a[low + cur] = b[cur];
        cur--;
    }
}

void mergeSort(int p, int r){


    std::vector<std::future<void>> thread_poolLocal;
    int q;

    if (p >= r) return;
    q = (p+r)/2;

    thread_poolLocal.push_back( std::async(launch::async, mergeSort, p, q));
    thread_poolLocal.push_back( std::async(launch::async, mergeSort, q+1, r));

    merge(p, q, r);
}

int main()
{
    arrayLen = (sizeof(a)/sizeof(*a));
    cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << endl;

    int i;
    for (i = 0; i < arrayLen; i++) printf ("%d ", a[i]);
    cout << "\n" << endl;
    mergeSort(0, arrayLen);

    for (i = 0; i < arrayLen; i++) printf ("%d ", a[i]);

    return 0;
}

When I test this with the simple array shown above, the output is:

Length of array = 10
10 9 8 7 6 5 4 3 2 1

0 1 4 2 3 10 5 6 9 7 

I am compiling the program with: g++ mergeSortThreaded.cpp -o mergeSortThreaded -std=c++0x -pthread

What am I doing wrong here?

You push 2 threads into thread_poolLocal then immediately call merge (which needs the results of those threads) before the threads have ended.

This code can lead to an explosion of threads with larger arrays being sorted because every call to mergeSort will create 2 more threads until you get down to empty regions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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