从main中的对象成员函数生成线程

时间:2015-04-30 05:22:57

标签: c++ multithreading

我一直在尝试使用线程并遇到一个我似乎无法修复的问题。我试图从一个带参数的成员函数中生成一个线程但是我还没有能够让它不会抛出错误。

继承我拥有的东西

ArraySorter s;
char *arr1, *arr2, *arr3;

arr1 = new char[MAXSIZE];
arr2 = new char[MAXSIZE];
arr3 = new char[MAXSIZE];

srand(time(NULL));

for (int i = 0; i < MAXSIZE; i++)
{
    arr1[i] = arr2[i] = arr3[i] = rand() % MAXSIZE;
}

thread t1(&ArraySorter::InsertionSort, &s, arr1, MAXSIZE);
thread t2(&ArraySorter.MergeSort, arr2, MAXSIZE);
thread t3(&s.QuickSort, arr3, MAXSIZE);

要清楚我的所有排序算法都按顺序采用char *和整数,产生上述线程的所有3种方法都不起作用,因为我尝试了我找到的解决方案,所以我不知所措。

声明:

static void InsertionSort(int* arr, int n, int startIndex, int gap);
static void InsertionSort(int* arr, int n);
static void MergeSort(int* arr, int n);
static void QuickSort(int* arr, int n);
static void ShellSort(int* arr, int n, int* gapVals, int gapValsCount);
static void QuickSort(int *arr, int high, int low);
static int GetPivot(int *arr, int high, int low);
static void MergeArray(int *arr, int high, int mid, int low);
static void MergeSort(int *arr, int high, int low);

1 个答案:

答案 0 :(得分:0)

  1. 您创建char数组并尝试传递char*,但函数需要int*。您需要在某处更改类型,或者创建排序函数模板。

  2. 您无法编译代码,因为thread构造函数无法推断出要使用的函数(例如void InsertionSort(int* arr, int n, int startIndex, int gap)void InsertionSort(int* arr, int n))。纠正它的一种方法是重命名函数。另一种方法是在answer中指定函数指针。

    void(*insertion_1)(int*, int)      = &ArraySorter::InsertionSort;
    void(*insertion_2)(int*, int, int) = &ArraySorter::InsertionSort;
    
  3. 查看简化示例的完整代码

    #include <iostream>
    #include <functional>
    #include <thread>
    
    using namespace std;
    
    #define MAXSIZE 128
    
    class ArraySorter {
    public:
        static void InsertionSort(int* arr, int n) {
        }
        static void InsertionSort(int* arr, int n1, int n2) {
        }
    };
    
    int main() {
        int* arr1 = new int[MAXSIZE];
        int* arr2 = new int[MAXSIZE];
        int* arr3 = new int[MAXSIZE];
    
        for (int i = 0; i < MAXSIZE; i++) {
            arr1[i] = arr2[i] = arr3[i] = rand() % MAXSIZE;
        }
    
        void(*insertion_1)(int*, int)      = &ArraySorter::InsertionSort;
        void(*insertion_2)(int*, int, int) = &ArraySorter::InsertionSort;
        thread t1(insertion_1, arr1, MAXSIZE);
        thread t2(insertion_2, arr1, MAXSIZE, 0);
        // Won't compile!
        // thread t3(&ArraySorter::InsertionSort, arr1, MAXSIZE);
    }