使用一个线程,我将什么传递给我的函数

时间:2011-03-08 01:47:49

标签: c++ multithreading unix g++ pthreads

  

可能重复:
  Error with passing a pointer using threads

我试图找出我传入函数的内容。

我不知道该怎么做,我以前从未使用过线程 问题区域已标记。

void matrixACreate(struct  a *);

void *status;  
struct a  
{
     int Arow; // Matrix A    
     int Acol; // WxX  
     int low; // Range low  
     int high;  
};  

int main(int argc, char * argv[])  
{   
    struct a matrix_mult_info;

    matrix_mult_info.Arow = atoi(argv[1]); // Matrix A
    matrix_mult_info.Acol = atoi(argv[2]); // WxX

    matrix_mult_info.low = atoi(argv[5]); // Range low
    matrix_mult_info.high = atoi(argv[6]);

    pthread_t matrixAthread;

    pthread_t runner;
    int error, retValue;

    //if (Acol != Brow)
    //{
    //   cout << " This matrix cannot be multiplied. FAIL" << endl;
    //   return 0;
    //}  
    //HERE IS THE PROBLEM IN THE NEXT LINE:  

    error = pthread_create(&matrixAthread, NULL, matrixACreate, matrix_mult_info );    
    // I don't know what to pass as the last parameter

    retValue = pthread_join(matrixAthread, &status);  
    return 0;  
}

void matrixACreate(struct a *matrix) {  
    struct a *data = (struct a *) malloc(sizeof(struct a));  
    data->Arow = matrix->Arow;  
    data->Acol = matrix->Acol;  
    int range = ((matrix->high - matrix->low) + 1);  
    cout << matrix->Arow << endl;  
    free(data);  
}  

1 个答案:

答案 0 :(得分:2)

将对数据的引用传递给线程:

pthread_create(&matrixAthread, NULL, matrixACreate, &matrix_mult_info);

然后在线程中作为pthread_create的最后一个参数给出的引用将是参数的值,您可以将其转换回传入的结构的数据类型:

void *matrixACreate(void *td)
{
    struct a *matrix = td;
}