我有该代码,想对其进行修改并将其放在类中,例如MergeSort
将其转换为类后,在initMergeSort的那一行中得到一个错误:
错误:没有匹配项将函数“ merge_sort”转换为“ void *()(void )” if(pthread_create(&thread,NULL,merge_sort,(void *)NULL)!= 0){
必须调用对非静态函数的引用(可能的调用目标
{Clion识别它* merge_sort})
pthread_create(&thread, NULL, merge_sort,(void *) NULL);
新标题
and the new header:
class MergeSort {
private:
//int *notSortedData;
int *sortedData{};
int part = 0;
void merge(int low, int mid, int high);
void merge_sort(int low, int high);
//Problem is here: --v
void *merge_sort(void *arg);
public:
MergeSort(int* notSortedData){
this->sortedData = notSortedData;
}
static const int MAX = 20;
static const int HALF_OF_MAX = MAX / 2;
int initMergeSort(/*int *notSortedData*/);
};
旧标题:
static const int MAX = 20 ;
static const int HALF_OF_MAX = MAX / 2;
void merge(int low, int mid, int high);
void merge_sort(int low, int high);
void *merge_sort(void *arg);
int initMergeSort(int *notSortedData);
// array of size MAX
int *a;
int part;
void merge(int low, int mid, int high) {(...)}
// merge sort function
void merge_sort(int low, int high) {
// calculating mid point of array
(...)
// calling first half
merge_sort(low, mid);
// calling second half
merge_sort(mid + 1, high);
// merging the two halves
merge(low, mid, high);
}
}
//多线程的线程功能问题在这里
---------------------- v
void *merge_sort(void *arg) {
// which part out of 4 parts
int thread_part = part++;
// calculating low and high
int low = thread_part * (MAX / 4);
int high = (thread_part + 1) * (MAX / 4) - 1;
// evaluating mid point
int mid = low + (high - low) / 2;
if (low < high) {
merge_sort(low, mid);
merge_sort(mid + 1, high);
merge(low, mid, high);
}
}
// merge function for merging two parts
int initMergeSort(int *notSortedData) {
a = notSortedData;
(...)
pthread_t threads[THREAD_MAX];
// creating 4 threads Here I have to invoke function call merge_sort
for (unsigned long &thread : threads) {
pthread_create(&thread, NULL, merge_sort,
(void *) NULL);
}
// joining all 4 threads
(...)
// merging the final 4 parts
merge(0, (HALF_OF_MAX - 1) / 2, HALF_OF_MAX - 1);
(...)
}
谢谢您
答案 0 :(得分:0)
您不能对pthread回调使用非静态类方法。非静态方法具有一个隐藏的this
参数,调用该方法时pthread无法解决该问题。
您需要使用静态方法(或非成员函数),例如:
class MergeSort {
private:
...
static void* static_merge_sort(void *arg);
void* merge_sort();
};
void* MergeSort::static_merge_sort(void *arg)
{
return ((MergeSort*)arg)->merge_sort();
}
void* MergeSort::merge_sort()
{
...
return ...;
}
pthread_create(&thread, NULL, &MergeSort::static_merge_sort, this);