一个多线程快速排序的程序调试
来源:百度知道 编辑:UC知道 时间:2024/05/13 02:47:19
#include <afxwin.h>
#include "stdafx.h"
using namespace std;
HANDLE hSemaphore;
template <class Item>
struct SortParam // 排序函数参数: data为待排数据的数组指针 num为数据的个数 sCount是最大并发线程数 Threshold是线程分割的阈值
{
Item* data;
int num;
int sCount;
int Threshold;
};
template <class Item> // 函数模板,Item是待排的数据类型
UINT MultiThreadQuickSort ( LPVOID pParam ) // 多线程快速排序算法,参数为pParam指向的SortParam结构
{
// 将传递过来的pParam所指向的参数正确读出
SortParam<Item>* pPara=(SortParam<Item>*) pParam;
Item* data=pPara->data;
int num=pPara->num;
int sCount=pPara->sCount;
int Threshold=pPara->Threshold;
if (num<=1)
return 0;
int i=0, j=num-1;
int pivot=data[0];
while(i<j)
{
while(data[j]>pivot&&(i<j))
j--;
if (i<j)<
问题在于没有进行同步,主函数在排序完成前就退出了。
用WaitForSingleObject以及WaitForMultipleObjects进行同步。
改动代码如下。
#include <afxwin.h>
#include "stdafx.h"
using namespace std;
HANDLE hSemaphore;
template <class Item>
struct SortParam // 排序函数参数: data为待排数据的数组指针 num为数据的个数 sCount是最大并发线程数 Threshold是线程分割的阈值
{
Item* data;
int num;
int sCount;
int Threshold;
};
template <class Item> // 函数模板,Item是待排的数据类型
UINT MultiThreadQuickSort ( LPVOID pParam ) // 多线程快速排序算法,参数为pParam指向的SortParam结构
{
HANDLE h1,h2; // <---加入这行,对两个线程进行监控
// 将传递过来的pParam所指向的参数正确读出
SortParam<Item>* pPara=(SortParam<Item>*) pParam;
Item* data=pPara->data;
int num=pPara->num;
int sCount=pPara->sCount;
int Threshold=pPara->Threshold;
if (num<=1)
return 0;
int i=0, j=num-1;
int pivot=data[0];
while