如何-使用文件锁对矩阵元素求和(unix-C/C ++) [英] How to - sum of matrix elements using file lock (unix - C/C++)

查看:63
本文介绍了如何-使用文件锁对矩阵元素求和(unix-C/C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 M [nxn] 矩阵,必须考虑以下条件来计算[n,n]点中元素的总和:
-随机选择行或列;
-sum它是该行或该列的最后一个元素中的元素,并将其他元素设置为0;

现在的问题是,我必须锁定正在使用的每一行或每一列,因为我需要使用多个过程来完成此总和.我怎么能解决呢?
我知道我必须使用 fcntl()和其他一些属于它的东西,但是我对解决它的方法很感兴趣.
(谢谢指教!)

I have an M[nxn] matrix and have to calculate the sum of the elements in the [n, n] point considering the following criteria:
-randomly choose a row or a column ;
-sum it's elements in the last element of that row or column and set the other elements to 0;

Now, the problem is, that I have to lock each row or column that I'm working with, because I need to do this sum using more than one process. How could I solve it?
I know that I have to use the fcntl() and some other things that belong to it, but I'm interested in the method of solving it.
(Thanks in advice !)

推荐答案

您实际上不需要锁定矩阵(除非其在文件中).如果它在文件中,我将首先将矩阵加载到内存中,然后您就不需要锁了.这样看:

You actually shouldn't need to lock the matrix (unless its in a file). If its in a file, I would just load the matrix into memory first and then you own't need a lock. Look at it this way:

如果您具有nxm矩阵,请让您的父进程从m个子进程中派生出来,然后等待子进程.

If you have an nxm matrix, have your parent process fork off m child processes and wait for the child processes.

在每个子进程中,让每个子进程占用m行中的每一行.

In each child process, have each one take each one of the m rows.

让每个子进程将每一行加起来,并将值设置为0,然后将总和放在最后一列中.

Have each child process add up each row, and set the values to 0 and put the sum in the last column.

结束每个子进程.

完成所有操作后,让您的父进程汇总该列的第n行.

When all are done, have your parent process sum up the nth row of the column.

由于所有子进程都将根据自己的数据集进行操作,因此它们将不需要锁定矩阵的任何部分,因为我们永远不会访问相同的内存区域.

Since all the child processes will be acting on their own data set, they won't need to lock any part of the matrix since we won't be accessing the same region of memory ever.

这篇关于如何-使用文件锁对矩阵元素求和(unix-C/C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆