我试图在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;
}
答案 0 :(得分:2)
你有一个错字
cerr << "create 2: " << pthread_create( &t1, NULL, &mergeSort, static_cast<void*>(m2)) << endl;
您应该使用t2
代替t1
作为第二个帖子。