C pthread没有同步执行其功能

C pthread没有同步执行其功能,c,parallel-processing,pthreads,mutex,synchronous,C,Parallel Processing,Pthreads,Mutex,Synchronous,所以我试图完成我的并行类的一个赋值,它涉及到使用Pthreads对一些数字求和 我有一个sum函数,我向它传递一个结构: void *partition(void* p){ ThreadData *a=malloc(sizeof(ThreadData)); a=(ThreadData*)p; int i = a->pid; int sum=0; int size = a->rows*a->cols; int row=a-&g

所以我试图完成我的并行类的一个赋值,它涉及到使用Pthreads对一些数字求和

我有一个sum函数,我向它传递一个结构:

void *partition(void* p){
    ThreadData *a=malloc(sizeof(ThreadData));
    a=(ThreadData*)p;

    int i = a->pid;

    int sum=0;

    int size = a->rows*a->cols;
    int row=a->pid/a->cols;
    int col=a->pid%a->cols;

    int partition_size = ((size / processors)+1);

    for(i;i<partition_size*processors;i+=processors){

        col = i%a->cols;
        row = i/a->cols;

        if (i<=size-1){
            sum+= matrix[row][col]+1;
            //printf("[%d][%d]%d +",row,col,matrix[row][col]);
        }


    }

    a->localsum=sum;
    printf("function sum: %d\n",sum);
    pthread_exit(NULL);
}
如您所见,为了产生所需的结果,我使用了sleep1;但是让程序在继续之前等待整整一秒钟完全违背了多线程并行计算的目的。这也使得互斥锁的使用毫无意义,我可以逐字逐句地注释掉它们,程序的功能也一样

从我在网络教程中看到的情况来看,这是很多人编写代码的方式,但对我来说似乎并不适用

那么,我如何在不使用sleep的情况下重写相同结果的代码呢


提前谢谢

在尝试使用它们的结果之前,您需要等待线程完成连接。我尝试在与创建相同的for循环中连接它们,但它似乎不起作用,这也没有意义。想想看。创建线程。让他们都跑吧。然后你就等他们全部完成。两个循环。@Csteele5你知道计算机按照你告诉它的顺序做事,对吗?所以,如果您在一个循环中创建并连接,那么它将是:创建线程1,等待线程1完成,创建线程2,等待线程2完成。。。。而你想要的是:创建线程1,创建线程2,…,等待线程1完成,等待线程2完成,…所以更像是我在帖子里写的那样。。。这很奇怪,因为如果我把打印语句和join放在一起,它们的工作顺序就不正常了。。。。如果你愿意,我可以贴张照片。。。事实上,许多函数可以异步运行。所以我在这里要问的是,如何准确地让它们以一种同步的方式运行,即使它们看起来是这样映射的。
int main(){


    int totalsum=0;
    void *status;
    ThreadData *g;
    g=malloc(processors*( sizeof(ThreadData)));
    int i;

    for(i=0;i<processors;i++){
        g[i].rows=rows;
        g[i].cols=cols;
        g[i].pid=i;
        g[i].localsum=0;
    }

    fillMatrix(rows, cols);

    pthread_t tid[processors];

    i;

    for(i=0;i<processors;i++){
        pthread_create(&tid[i],NULL,partition,(void *)&g[i]);
        sleep(1);

        pthread_mutex_lock(&mVar);
        totalsum+=g[i].localsum;
        pthread_mutex_unlock(&mVar);

    }
    for(i=0;i<processors;i++){
        pthread_join(tid[i],NULL);
    }

    printf("The sum of your Matrix is %d",totalsum);
}
function sum: 51
function sum: 40
function sum: 45
The sum of your Matrix is 136