为什么 pthread_join 在我的代码中不起作用?

问题描述 投票:0回答:0

对于课程,我必须进行线程合并排序,我在其中使用多个线程来帮助加速算法。我已经成功地进行了迭代合并排序,现在正在尝试使用线程。代码成功完成了 pthread_create() 函数,但随后出现错误。这是我的代码和错误:

#include <iostream>
#include <vector>
#include <pthread.h>

#include <algorithm>


using namespace std;


void * merge_sort(void * arg) {
    vector<int> *xs = (vector<int> *)arg;

    int unit = 1;
    int n = (int)xs->size();

    // main loop
    while (unit <= n) {

        // select the part of the vector that is going to be the main focus this loop
        for (int h = 0; h < n; h += 2 * unit) {
            int l = h;
            int r = min({n, h + 2 * unit});
            int mid = h + unit;
            int p = l;
            int q = mid;

            while (p < mid && q < r) {
                if (xs[p] <= xs[q]) {
                    p++;
                } else {
                    int tmp = xs->at(q);

                    // Change the vector
                    for (int i = q - p; i > 0; i--) {
                        xs[p + i] = xs[p - 1 + i];
                    }

                    xs->at(p) = tmp;
                    p++;
                    mid++;
                    q++;
                }
            }
        }
        unit *= 2;
    }
    return 0;
}


void txt(vector<int> v, int vector_size){
    for (int i=0; i<vector_size; i++){
        cout << v[i] << " ";
    }
    cout << endl;
}


int main(){
    vector<int> v = {9, 8, 7, 6, 5, 4, 3, 2, 1};

    int vector_size = (int)v.size();
    cout << "before sort:";
    txt(v, vector_size);

    int number_of_threads = 2;
    pthread_t thread[number_of_threads];

    for (int i = 0; i < number_of_threads; i++){
        pthread_create(&thread[i], NULL, merge_sort, &v[i]);
        cout << "pthread_create done" << endl;
        pthread_join(thread[i], NULL);
        cout << "pthread_join done" << endl;
    }
    
    cout << "after sort:";
    txt(v, vector_size);
    return 0;
}

Process finished with exit code -1073741819 (0xC0000005)

这里有什么问题?

c++ multithreading clion
© www.soinside.com 2019 - 2024. All rights reserved.