C Pthread比单线程花费更长的时间

时间:2019-12-09 11:51:29

标签: c multithreading matrix pthreads matrix-multiplication

我编写了一个矩阵乘法器代码,旨在量化每种矩阵大小的线程化速度。下面是创建和执行线程的代码。我是线程技术的新手,但是每当我使用线程时,它似乎要花费大约12倍的时间,这是我做错了还是有人知道为什么它这么慢?

谢谢

void *vectorMultiply(void *arguments){
    struct vectorV *args = arguments;

    int sum = 0;
    for (int iii = 0; iii < args->n; iii++) {
        sum = sum + args->first[args->i][iii] * args->second[iii][args->ii];
    }
    args->out[args->i][args->ii] = sum;
}

void singleThreadVectorMultiply(int n,int i,int ii, int 
                                **first, int **second, int **out){
    int sum = 0;
    for (int iii = 0; iii < n; iii++) {
        sum = sum + first[i][iii] * second[iii][ii];
    }
    out[i][ii] = sum;
}

void multiplyMatrix(int n, int** first, int** second, int** out){
    pthread_t tid[n][n]; 
    struct vectorV values[n][n];
    for (int i = 0; i < n; i++) {
        for (int ii = 0; ii < n; ii++) {
            if(!SINGLETHREAD){
                values[i][ii].n=n;
                values[i][ii].i=i;
                values[i][ii].ii=ii;
                values[i][ii].first = first;
                values[i][ii].second=second;
                values[i][ii].out=out;
                pthread_create(&tid[i][ii], NULL, vectorMultiply, 
                              (void *)&values[i][ii]); 
            }
            else{
                clock_t time; 
                time = clock(); 
                singleThreadVectorMultiply(n,i,ii,first,second,out);
                time = clock() - time; 
                totalTime+=time;
            }

        }
    }
    if(!SINGLETHREAD){
        clock_t time; 
        time = clock(); 
        for(int i=0; i < n; i++)
            for(int ii=0; ii < n; ii++)
                pthread_join( tid[i][ii], NULL); 
        time = clock() - time; 
        totalTime+=time;
    }
}

0 个答案:

没有答案