【问题标题】:Using a thread, what do I pass into my function [duplicate]使用线程,我应该将什么传递给我的函数[重复]
【发布时间】:2011-03-08 01:47:49
【问题描述】:

可能重复:
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);  
}  

【问题讨论】:

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


【解决方案1】:

将对您的数据的引用传递到线程中:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2012-06-23
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 2017-01-06
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多