c - 使用管道将两个矩阵相乘

标签 c matrix pipe

我想编写一个程序来为每个变量使用管道将两个矩阵相乘,但我的代码无法正常工作。

有什么问题吗?

child 和 parent 不一样;既不是他们的列和行,也不是他们的变量。

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

int first[10][10], second[10][10], m[10][10];
int r1,r2,c1,c2;

struct mat
{
int i,j,r;
};

int writer(int fd[],struct mat l)
{
    usleep(300000);
    close(fd[0]);
    int y;
    for(y=0;y<c1;y++)
    {
        l.r+=first[l.i][y]*second[y][l.j];
    }
    write(fd[1], &l,sizeof(l));
    printf("child [%d][%d] write %d \n " ,l.i,l.j, l.r);
}

void reader(int fd[])
{
    struct mat p;
    close(fd[1]);
    read(fd[0],&p,sizeof(p));
    printf(" Parent [%d][%d] reads %d \n ",p.i,p.j, p.r);
    m[p.i][p.j]=p.r;
    usleep(3000000);
}

主要函数是:

int main()
{

int a,b,j,i;
int fd[2];
pid_t cp;
pipe(fd);
\\read two matrices

    for(i=0;i<r1;i++)
    {
         for(j=0;j<c2;j++)
         {
                cp=fork();      
                if(cp==0)
                {
                    printf("k\n");
                    struct mat m;
                    m.r=0;
                    m.i=i;
                    m.j=j;
                    writer(fd,m);
                }
                if(cp!=0)
                {
                    sleep(2);
                    reader(fd);
                }    
        }   
        return 0;
        sleep(100);
    }
}   

最佳答案

您的程序遇到的第一个问题是:main 中的 for 循环没有运行(尝试在第一个 for 循环下面放置一个 printf("Entering For Loop")

for(i=0;i<r1;i++)

这是因为索引变量正在与未初始化的 r1 进行比较,这在理论上是一个“垃圾”值,但实际上,由于这是第一次使用该地址,因此它是零。所以 for 循环中的代码永远不会执行。确保您所有的 for 循环都遵循此规则。

关于c - 使用管道将两个矩阵相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385779/

相关文章:

python - 混合类型的 NumPy 数组/矩阵

matlab - 查找 3 维矩阵(或 n 维)中最小元素的索引

arrays - 将Powershell中的对象重定向到其他功能

ios - 如何快速创建 3D 数组/矩阵?

Ruby 在文件和标准输入之间切换

c - 开管警告

c - C中的 "passing argument 2 of strcmp makes pointer from integer without a cast"错误是什么意思?

c - 多线程C程序中串口的调度和访问控制

c - 中点圆算法不适用于不等中心坐标

python - 在 Python 的 Cython 方法中传递整数列表的 numpy 数组