我创建了一个适用于非重复整数数组的合并排序。我正在尝试制作相同的多线程版本。
我得到了无效的结果。
void mergesort(int data[ ], size_t n)
{
size_t n1; // Size of the first subarray
size_t n2; // Size of the second subarray
if (n > 1)
{
// Compute sizes of the subarrays.
n1 = n / 2;
n2 = n - n1;
mergesort(data, n1); // Sort from data[0] through data[n1-1]
mergesort((data + n1), n2); // Sort from data[n1] to the end
// Merge the two sorted halves.
merge(data, n1, n2);
}
}
DWORD WINAPI threadedmergesort(LPVOID params)
{
size_t n1; // Size of the first subarray
size_t n2; // Size of the second subarray
Params* parameters = (Params*) params;
if (parameters->size > 1)
{
// Compute sizes of the subarrays.
n1 = parameters->size / 2;
n2 = parameters->size - n1;
Params* p1 = new Params(parameters->dataArray, n1);
//mergesort(data, n1); // Sort from data[0] through data[n1-1]
HANDLE h1 = CreateThread(NULL, 0, threadedmergesort, (LPVOID)p1, 0, NULL);
Params* p2 = new Params(parameters->dataArray, n2);
//mergesort((data + n1), n2); // Sort from data[n1] to the end
HANDLE h2 = CreateThread(NULL, 0, threadedmergesort, (LPVOID)p1, 0, NULL);
WaitForSingleObject(h1, INFINITE);
WaitForSingleObject(h2, INFINITE);
// Merge the two sorted halves.
merge(parameters->dataArray, n1, n2);
}
return (DWORD)0x0; //null
}
struct Params
{
int* dataArray;
int size;
Params(int _dataArray[], int _size);
};
Params::Params(int _dataArray[], int _size)
{
dataArray = _dataArray;
size = _size;
}
有人可以评论为什么我会使用合并排序的线程版本得到无效的结果,以及我可以做些什么来纠正这个问题?