【发布时间】: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