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

- 39
- 9
1 Answers
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:
If you have an nxm matrix, have your parent process fork off m child processes and wait for the child processes.
In each child process, have each one take each one of the m rows.
Have each child process add up each row, and set the values to 0 and put the sum in the last column.
End each child process.
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.

- 2,796
- 3
- 24
- 39
-
Thanks for your reply. Actually, it could be done like this, but my task is to randomly select a row/column and sum in that way and I need to lock that row/column to avoid duplication. – Adorjan Jun 14 '13 at 15:03
-
int ret = fcntl(fd, F_SETLKW, &lock); will lock that file descriptor for writing. You can then write to the file while still reading it with the other threads. – KrisSodroski Jun 14 '13 at 16:51