我正在编写一个程序,该程序使用线程来计算一维数组的数组产量,所有维都等于“ n”。
每个线程必须计算具有该一维数组的数组行的产生。
我得到的输出似乎有地址值,而不是已经作为矩阵元素输入的值。
我究竟做错了什么?
这是我写的代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define mat_dim 5

static struct param
{
    int mat[mat_dim][mat_dim];
    int vec[mat_dim];
    int ind;
    int alter[mat_dim];
};

void *Calculate_row(struct param tid)
{
    int i;
    for (i=0; i<5; i++) {
        tid.alter[tid.ind] = tid.alter[tid.ind]+tid.mat[tid.ind][i]*tid.vec[i];
    }
    pthread_exit((void *)&tid);
}

int main (int argc, char *argv[])
{
    pthread_t thread[mat_dim];
    pthread_attr_t attr;
    int rc;
    long t;
    void *status;
    int th_array[5][5]={{1,4,3,5,1},{4,6,2,8,5},{3,5,1,3,6},{1,5,6,2,8},{4,7,5,3,6}};
    int th_vec[5]={1,2,1,2,1};
    struct param thread_parameter;
    thread_parameter.mat[5][5]=th_array;
    thread_parameter.vec[5]=th_vec;
    int tmp[5]={0,0,0,0,0};
    thread_parameter.alter[5]=tmp;
    /* Initialize and set thread detached attribute */
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    for(t=0; t<mat_dim; t++) {
        printf("Main: creating thread %ld\n", t);
        thread_parameter.ind=t;
        rc = pthread_create(&thread[t], &attr, Calculate_row,&thread_parameter);
        if (rc) {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    /* Free attribute and wait for the other threads */
    pthread_attr_destroy(&attr);
    printf("the result vector is : ");
    for(t=0; t<mat_dim; t++) {
        rc = pthread_join(thread[t], NULL);
        if (rc) {
            printf("ERROR; return code from pthread_join() is %d\n", rc);
            exit(-1);
        }
        printf("%d, ",thread_parameter.alter[t]);
    }

    printf("Main: program completed. Exiting.\n");
    pthread_exit(NULL);
}

最佳答案

您正在调用rc = pthread_create(&thread [t],&attr,Calculate_row和&thread_parameter);
哪里
struct param thread_parameter;

并且函数无效* Calculate_row(struct param tid)
它应该是空的* Calculate_row(struct param * tid)
随着指针的传递并改变全部。到->。

10-07 18:51
查看更多