pthread_join() 可以导致顺序执行吗?

标签 c malloc free pthread-join

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

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

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

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

#define M 3 
#define K 2  
#define N 3 

int A[M][K] = {{1,4}, {2,5}, {3,6}}; 
int B[K][N] =  {{8,7,6}, {5,4,3}}; 
int C[M][N]; 

struct coords 
{ 
    int  i ;  /*  row  */       
    int  j ;  /*  column  */ 
}; 

//thread function
void* calc_val(void* resultCoords)
{
    int n, result = 0;
    struct coords **matCoords = (struct coords**) resultCoords;
    for(n = 0; n < K; n++)
    {
        result += A[(*matCoords)->i][n] * B[n][(*matCoords)->j];
    }
    C[(*matCoords)->i][(*matCoords)->j] = result;
    // One more question: 
    // <- Should I free mem from malloc here? 
}

int main(int argc, char** argv) 
{
    int numThreads = M * N, threadIndex = 0, i, j;
    pthread_t threads[numThreads];
    pthread_attr_t attributes[numThreads];
    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);
            pthread_join(threads[threadIndex], NULL); // <-Main Question
            threadIndex++;
        }
    }

    /* ... */

    return (EXIT_SUCCESS);
}

最佳答案

在您的代码中,您基本上执行以下操作:

  1. 为线程准备一些数据
  2. 运行线程
  3. 等待完成
  4. 进入下一次迭代

所以这段代码绝对是连续的

要使其非连续,您需要这样的东西:

  1. 准备一些数据
  2. 运行线程
  3. 进入下一次迭代
  4. 等待所有线程完成

尝试这样的事情:

   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);

关于内存分配的下一个问题 - 您可以在所有线程完成时执行此操作(然后您需要将所有分配的指针存储在某处),或者您可以按照评论中的要求释放每个线程

关于pthread_join() 可以导致顺序执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329013/

相关文章:

c - c中的动态数组

c - 如何检查变量是否为 C 中的 "const"限定符类型?

c - 传递许多变量与传递结构

c - c 中的 malloc() 和 free() 数组

c - malloc 到 "array"指针的元素

C malloc 和 free

c - 为什么 pthread 返回的值与传递给线程函数的值不同?

c - 什么时候使用 valloc() 而不是 malloc() 更合适?

c - C 函数中的 malloc 和自由指针

c - 释放使用双指针分配的结构数组