[英]Multithreaded QuickSort
对不起,上一个问题。 当我是新手时,我不知道如何在堆栈溢出时发布问题。 这是我使用Pthread完成的多线程快速排序的代码。 但是它不能正常工作。
#include <iostream>
#include <pthread.h>
#define max 20
using namespace std;
class quick
{
int arr[max];
int n;
public:
int high;
int low;
quick(int n1)
{
n=n1;
}
quick(quick *obj)
{
this->n=obj->n;
int i;
for(i=0;i<this->n;i++)
{
this->arr[i]=obj->arr[i];
}
}
void accept();
void display();
void quicksort(int,int);
int partition(int,int);
static void* thread_function(void *ptr)
{
quick* q= static_cast<quick *>(ptr);
q->quicksort(q->low,q->high);
}
};
void quick :: accept()
{
int i;
for(i=0;i<n;i++)
{
cout<<"Enter data: "<<endl;
cin>>arr[i];
}
}
void quick :: display()
{
int i;
cout<<"The array is: "<<endl;
for(i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
void quick :: quicksort(int low,int high)
{
int piv_index;
pthread_t th1,th2;
quick *q1,*q2;
if(low<high)
{
piv_index=partition(low,high);
q1= new quick(this);
q2= new quick(this);
q1->low=low;
q1->high=piv_index-1;
q2->low=piv_index+1;
q2->high=high;
void *obj1=reinterpret_cast<void *>(q1);
void *obj2=reinterpret_cast<void *>(q2);
pthread_create(&th1,NULL,quick :: thread_function,(void *)obj1);
pthread_create(&th2,NULL,quick :: thread_function,(void *)obj2);
pthread_join(th1,NULL);
pthread_join(th2,NULL);
}
}
int quick :: partition(int low,int high)
{
int i,j,pivot,temp;
pivot=arr[low];
i=low+1;
j=high;
while(i<=j)
{
while(arr[i]<=pivot)
i++;
while(arr[j]>pivot)
j--;
if(i<j)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
arr[low]=arr[j];
arr[j]=pivot;
return j;
}
int main()
{
int no;
cout<<"Enter the size of array: "<<endl;
cin>>no;
quick *q;
q= new quick(no);
q->accept();
cout<<"Before Sorting: "<<endl;
q->display();
q->low=0;
q->high=no-1;
void *ptr=reinterpret_cast<void *>(q);
quick::thread_function(ptr);
cout<<"After Sorting: "<<endl;
q->display();
return 0;
}
output:
Enter the size of array:
5
Enter data:
5
Enter data:
4
Enter data:
3
Enter data:
2
Enter data:
1
Before Sorting:
The array is:
5 4 3 2 1
After Sorting:
The array is:
1 4 3 2 5
请帮助我弄清楚到底是什么错误...提前谢谢
给定这些定义:
void *obj1=reinterpret_cast<void *>(q1);
void *obj2=reinterpret_cast<void *>(q2);
似乎您正在将void **投射到下面的void *。 我认为您不是要这样做:
pthread_create(&th1,NULL,quick :: thread_function,(void *)&obj1);
pthread_create(&th2,NULL,quick :: thread_function,(void *)&obj2);
删除&符,看看是否有帮助。
编辑:
另外,看起来您的构造函数quick
就从源对象复制了数组,而且我看不到任何将其复制回原始对象的东西,因此这些结果丢失了。 最好单独存储该数组,并从一个quick
指针传递到下一个指针,以使它们都对数据的同一副本进行操作。
编辑(2):
快速而肮脏的方式:
移动int arr[max];
从quick
到内部main
。 将int *arr;
quick
进入。 像这样更改构造函数:
quick(int n1, int *a)
{
n=n1;
arr = a;
}
quick(quick *obj)
{
this->n=obj->n;
this->arr = obj->arr;
}
最后,将main
的q
分配更改为q= new quick(no, arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.