C pthread_join()会导致顺序执行吗?

C pthread_join()会导致顺序执行吗?,c,malloc,free,pthread-join,C,Malloc,Free,Pthread Join,当我使用pthread_join()时,我不确定它是否位于正确的位置。现在,它是否会等待线程退出,然后再次迭代循环?我想我要问的是,我是否应该将它从double for循环中去掉,并在pthread_join()之后直接创建一个新的for循环 PS:我对线程和C语言都很陌生。我还有另一个关于释放malloc内容的问题(在代码中作为注释)。我不确定在哪里使用free关键字,因为malloc结果指针在内部for循环的每次迭代后都会消失 这是我的密码。它用于两个预定义矩阵(a和B)上的矩阵乘法。(老师

当我使用pthread_join()时,我不确定它是否位于正确的位置。现在,它是否会等待线程退出,然后再次迭代循环?我想我要问的是,我是否应该将它从double for循环中去掉,并在pthread_join()之后直接创建一个新的for循环

PS:我对线程和C语言都很陌生。我还有另一个关于释放malloc内容的问题(在代码中作为注释)。我不确定在哪里使用free关键字,因为malloc结果指针在内部for循环的每次迭代后都会消失

这是我的密码。它用于两个预定义矩阵(a和B)上的矩阵乘法。(老师希望我们这样做)

#包括
#包括
#包括
#定义m3
#定义k2
#定义n3
int A[M][K]={{1,4},{2,5},{3,6};
int B[K][N]={{8,7,6},{5,4,3};
国际货币基金组织[M][N];
结构坐标
{ 
int i;/*行*/
int j;/*列*/
}; 
//线程函数
void*计算值(void*结果词)
{
int n,结果=0;
结构coords**matCoords=(结构coords**)结果词;
对于(n=0;ni][n]*B[n][(*matCoords)->j];
}
C[(*matCoords)->i][(*matCoords)->j]=结果;
//还有一个问题:
//i=i;
数据->j=j;
pthread_attr_init(&attributes[threadIndex]);
pthread_创建(
&线程[线程索引],
&属性[threadIndex],
计算值,
&数据);

pthread_join(threads[threadIndex],NULL);//在代码中,您基本上执行以下操作:

  • 为线程准备一些数据
  • 运行线程
  • 等它完成
  • 转到下一个迭代
  • 所以这段代码是绝对顺序的

    要使其不连续,您需要以下内容:

       for (i = 0; i < M; i++)
       {
            for(j = 0; j < N; j++)
            {
                struct coords *data = (struct coords*)malloc(sizeof(struct coords));
                data->i = i;
                data->j = j;
                pthread_attr_init(&attributes[threadIndex]);
                pthread_create(&threads[threadIndex], &attributes[threadIndex], calc_val, &data);
                threadIndex++;
            }
        }
        for (i=0;i<numThreads;i++)
            pthread_join(threads[i], NULL);
    
  • 准备一些数据
  • 运行线程
  • 转到下一个迭代
  • 等待所有线程完成
  • 试着这样做:

       for (i = 0; i < M; i++)
       {
            for(j = 0; j < N; j++)
            {
                struct coords *data = (struct coords*)malloc(sizeof(struct coords));
                data->i = i;
                data->j = j;
                pthread_attr_init(&attributes[threadIndex]);
                pthread_create(&threads[threadIndex], &attributes[threadIndex], calc_val, &data);
                threadIndex++;
            }
        }
        for (i=0;i<numThreads;i++)
            pthread_join(threads[i], NULL);
    
    (i=0;i { 对于(j=0;ji=i; 数据->j=j; pthread_attr_init(&attributes[threadIndex]); pthread_创建(&threads[threadIndex]、&attributes[threadIndex]、计算值和数据); threadIndex++; } }
    对于(i=0;iOW,感谢您的快速响应-您的真棒!这正是我想要的答案。这有助于我更好地理解pthread_join。编辑:对于释放malloc-我在thread函数中尝试了它,但得到了奇怪的结果,但您的第一个建议非常有效。您是尝试免费(resultwords)还是免费(matCoords)?第一个应该只起作用哦,好的。是的,我是免费的(*matCoords);