0
我想在C++中使用pthread。
我用pthread寫了一個mergesort,但有時在pthread_join中,我的代碼有分段錯誤。 (見代碼調試信息)
例如,用於輸入:
c + + pthread連接有時不起作用
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;
}
噢!
非常感謝! :) – user3541386
接受答案:) – Salgar