【发布时间】:2015-12-27 19:04:09
【问题描述】:
我有一个任务是使用共享内存使用叉子进行矩阵乘法,然后将时间结果与没有叉子的乘法进行比较,所以这里是没有它们的乘法:
int matrizA[Am][An];
int matrizB[An][Bp];
//here i fill the matrix from a .txt file
int matrizR[Am][Bp];
int a,b,c;
for (a=0; a < Am; a++){
for (b = 0; b < Bp; b++)
{
matrizR[a][b] = 0;
for (c=0; c<An; c++){
matrizR[a][b] += matrizA[a][c] * matrizB[c][b];
}
}
}
然后我尝试实现fork,但结果错误,我不确定我是否必须实现共享内存以及matrizA、matrizB和matrizR2应该在哪里共享?我是怎么做到的?
int matrizR2[Am][Bp];
pid_t pids[Am][Bp];
int h,j;
/* Start children. */TY
for (h = 0; h < Am; ++h) {
for (j=0; j<Bp ; ++j){
if ((pids[h][j] = fork()) < 0) {
perror("fork");
abort();
} else if (pids[h][j] == 0) {
matrizR2[h][j] = 0;
for (c=0; c<An; c++){
matrizR2[h][j] += matrizA[h][c] * matrizB[c][j];
}
printf("im fork %d,%d\n",h,j);
exit(0);
}
}
}
/* Wait for children to exit. */
int status;
pid_t pid;
while (n > 0) {
pid = wait(&status);
--n;
}
【问题讨论】:
-
当你fork一个新进程时,实际上是创建了一个新的进程,任何进程的内存都与任何其他进程是分开的。所以是的,你需要共享内存,或者你可以使用 threads 来代替。
-
在这个例子中如何实现共享内存?我读了这个,但真的不明白它必须link
-
@Stas 就像那个例子一样,我的 glob_var 应该是所有矩阵?我如何初始化它们?
-
必须使用进程和共享内存是否是要求?否则线程会容易得多。
标签: c fork shared-memory