0

我有以下代码会导致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;
}
4

1 回答 1

1

您正在加入自己,因为最后一个线程没有启动,而是使用创建其他线程的线程。检查 pthread_join 的错误代码...

于 2012-12-14T20:19:09.810 回答