我有以下代码在pthread_join
次调用时导致段错误。对不起,我很抱歉,但每一个字母都很重要。如果它很重要,那么相同的代码在WinAPI下运行良好且没有任何错误。
void solution_of_matrix(int amount_of_threads, vector< vector<double> > &matrix)
{
pthread_t * threads = new pthread_t[amount_of_threads - 1];
matrix_struct * data = new matrix_struct[amount_of_threads];
/* ... */
for (size_t i = 0; i < amount_of_threads; ++i)
{
/* ... */
if (i == amount_of_threads - 1)
{
MyThreadProc(&data[i]);
}
else
{
pthread_create(&threads[i], 0, MyThreadProc, &data[i]);
}
}
for(int i = 0; i < amount_of_threads; ++i)
pthread_join(threads[i], 0); // <- ERROR
delete[] threads;
delete[] data;
}
MyThreadProc
:
void* MyThreadProc(void* lpParam)
{
matrix_struct * data = (matrix_struct*)lpParam;
/*... */
pthread_mutex_lock(&mutex);
for (i = (data->i); i < (*data->matrix).size(); i++)
{
if ((*data->matrix)[i][i] == 0 )
for (j = (data->i + 1); j <(*data->matrix).size(); j++)
if ((*data->matrix)[j][i] != 0 )
{
vector< double > v;
for(size_t k = 0; k < (*data->matrix)[j].size(); ++k)
v.push_back((*data->matrix)[j][k]);
for( int q = 0; q < (*data->matrix)[j].size(); q++)
(*data->matrix)[j][q] = (*data->matrix)[i][q];
for ( int w = 0; w < (*data->matrix)[i].size(); w++)
(*data->matrix)[i][w] = v[w];
break;
}
}
for (i = (data->i); i < data->i + data->sz ; i++)
{
if ( i !=(*data->matrix).size() - 1)
{
tmp = (*data->matrix)[i][i];
for (j = n; j >= i; j--)
(*data->matrix)[i][j] /= tmp;
for (j = i+1; j < n; j++)
{
tmp = (*data->matrix)[j][i];
for (k = n; k >= i; k--)
(*data->matrix)[j][k] -= tmp*(*data->matrix)[i][k];
}
}
}
pthread_mutex_unlock(&mutex);
return 0;
}
在许多代码的末尾,我的struct
:
struct matrix_struct
{
vector< vector<double> > * matrix;
size_t i, sz;
};
工作选项是:
void solution_of_matrix(int amount_of_threads, vector< vector<double> > &matrix)
{
pthread_t * threads = new pthread_t[amount_of_threads];
matrix_struct * data = new matrix_struct[amount_of_threads];
/* ... */
for (size_t i = 0; i < amount_of_threads; ++i)
{
/* ... */
pthread_create(&threads[i], 0, MyThreadProc, &data[i]); //just simplifyed
}
for(int i = 0; i < amount_of_threads; ++i)
pthread_join(threads[i], 0);
delete[] threads;
delete[] data;
}
答案 0 :(得分:1)
您正在加入自己,因为最后一个线程未启动但使用创建其他线程的线程。检查pthread_join的错误代码......