我正在尝试在c ++中使用pthread。
我用pthread编写了mergesort,但是有时在pthread_join中,我的代码存在分段错误。 (请参阅代码调试信息)
例如,用于输入:

4
5 1 2 3


输出为:

** size is more than 2 **
I'm alive!
create 1: 0
create 2: 0
After creating!
i want to exit ... 2 1
i want to exit ... 2 2
join 1: 0
Segmentation fault


当要加入pthead 2时,发生分段错误。
提前致谢!

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<pthread.h>
using namespace std;

struct toSort
{
    int size;
    int * arr;
    toSort(int _size = 0, int * _arr = NULL)
    {
        size = _size;
        arr = _arr;
    }
};

void * mergeSort(void *args)
{
    toSort * m = static_cast<toSort*>(args);
    if(m -> size == 1)
    {
        pthread_exit(NULL);
    }
    else if(m -> size == 2)
    {
        if(*(m -> arr) > *((m -> arr) + 1))
        {
            int temp = *(m -> arr);
            * (m -> arr) = *((m -> arr) + 1);
            * ((m -> arr) + 1) = temp;
        }
    }
    else
    {
        cerr << "** size is more than 2 **" << endl;
        int ind = (m -> size) / 2;
        pthread_t t1, t2;
        toSort *m1, *m2;
        m1 = new toSort(ind, (m -> arr));
        m2 = new toSort((m -> size) - ind, ((m -> arr) + ind));
        cerr << "I'm alive!" << endl;
        cerr << "create 1: " << pthread_create( &t1, NULL, &mergeSort, static_cast<void*>(m1)) << endl;
        cerr << "create 2: " << pthread_create( &t1, NULL, &mergeSort, static_cast<void*>(m2)) << endl;
        cerr << "After creating!" << endl;
        cerr << "join 1: " << pthread_join(t1, NULL) << endl;
        cerr << "join 2: " << pthread_join(t2, NULL) << endl;
        cerr << "After join!" << endl;
        // merge(m -> arr, ind, m -> size);
    }
    cout << "i want to exit ... " << (m -> size) << " " << (*(m -> arr)) << endl;
    pthread_exit(NULL);
    return 0;
}

int main()
{
    int n, arr[100];
    // Read
    cin >> n;
    for(int i = 0; i < n; i++)
        cin >> arr[i];

    // Solve
    toSort * ans = new toSort(n, arr);
    pthread_t getAns;
    pthread_create( &getAns, NULL, &mergeSort, static_cast<void*>(ans));
    pthread_join(getAns, NULL);
    // Write
    for(int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
    return 0;
}

最佳答案

你有错字

cerr << "create 2: " << pthread_create( &t1, NULL, &mergeSort, static_cast<void*>(m2)) << endl;

您应该在第二个线程中使用t2而不是t1

关于c++ - C++ pthread连接有时不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23111221/

10-16 11:54