【问题标题】:Merge sort wih pthreads not working in c++合并排序与 pthreads 在 C++ 中不起作用
【发布时间】:2017-03-12 21:02:55
【问题描述】:

我有这个代码。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
using namespace std;


int N;
int* a ;
/* structure for array index
 * used to keep low/high end of sub arrays
 */
typedef struct Arr
{
    int low;
    int high;
} ArrayIndex;

void merge(int low, int high)
{
    int mid = (low+high)/2;
    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[right++];
        else
            b[cur++] = a[right++];
    }

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

void * mergesort(void *a)
{

    ArrayIndex *pa = (ArrayIndex *)a;
    int mid = (pa->low + pa->high)/2;

    ArrayIndex aIndex[N];
    pthread_t thread[N];

    aIndex[0].low = pa->low;
    aIndex[0].high = mid;

    aIndex[1].low = mid+1;
    aIndex[1].high = pa->high;

    if (pa->low >= pa->high) return 0;

    int i;
    for(i = 0; i < N; i++) pthread_create(&thread[i], NULL, mergesort, &aIndex[i]);
    for(i = 0; i < N; i++) pthread_join(thread[i], NULL);

    merge(pa->low, pa->high);

    //pthread_exit(NULL);
    return 0;
}

int main()
{
    int s;
    cout << "\nPlease enter a number of threads:" << endl;
    cout << "-> ";
    cin >> N;
    do
    {
        cout << "\nPlease enter the array size:" << endl;
        cout << "-> ";
        cin >> s;
        if(s%N != 0)
        {
            cout << "\n Number not divisible by: "<< N << endl;
        }
    }
    while (s%N != 0);
    a = new int[s];  // Allocate n ints and save ptr in a.
    for (int i=0; i<s; i++)
    {
        a[i] = rand() % 100 + 1;;    // Initialize all elements to zero.
       // printf ("%d ", a[i]);
    }
    ArrayIndex ai;
    ai.low = 0;
    ai.high = sizeof(a)/sizeof(a[0])-1;
    pthread_t thread;

    pthread_create(&thread, NULL, mergesort, &ai);
    pthread_join(thread, NULL);

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

    return 0;
}

所以基本上代码会询问用户线程的数量,然后是数组的大小,并且必须对数组进行排序。问题是合并排序不起作用,当我打印数组时没有排序。

【问题讨论】:

  • 这冒犯了我的 C++ 敏感性。为什么不给函数提供它们操作的参数呢?为什么不给他们一个合适的类型呢?
  • @CaptainGiraffe 抱歉冒犯了您的 C++ 敏感性,我正在尝试学习新事物。我知道这不是进行合并排序的最佳方法:)

标签: c++ arrays pthreads mergesort


【解决方案1】:

我发现了一个错误:

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

如您所见,ifelse 部分执行 完全相同的事情。
可能还有其他错误,提示是首先将算法转换为 不使用线程,
并在调试器中逐步执行算法。

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2016-08-19
    相关资源
    最近更新 更多