parfor loop & fprint not working

28 views (last 30 days)
Chris
Chris on 27 Aug 2011
I have two nested loops
The top loop is a parfor loop the inner loop is a regular for
I am trying to write the results to a file using fprintf, comma seperated. If I eliminate the parfor and make the loop a for loop the file is written properly; however speed is dramatically reduced on my quad core computer. When I change to parfor, the output on some lines is perfect and others is messed up. Part of the line on one with some of another in the middle and the rest in the end. I think this is because the two processes are writing at the same time. Is there a way to resolve this. I tried opening the file with
fname = fopen('result.csv', 'a'); and fname = fopen('result.csv', 'w');
I tried putting the open and close outside of the loop, in the outer loop and in the inner loop but this didn't resolve

Accepted Answer

Walter Roberson
Walter Roberson on 28 Aug 2011
In theory if you use fopen() for any valid permission that includes 'a', then this should not happen -- but the guarantee only holds if you use a single fprintf() or (better yet) fwrite() to send complete units of output. If you were using several consecutive fprintf() to construct single line of output, then then problem could come up: each call is atomic, but each line is not atomic. (Which is partly because MATLAB's fprintf() does not map exactly on to POSIX's fprintf() )

More Answers (1)

Titus Edelhofer
Titus Edelhofer on 27 Aug 2011
Hi,
exactly: your code put's in arbitrary order at arbitrary times lines into the file (interupting each other). I would suggest to do the following: inside your parfor loop put the output instead of into a file in some cellarray and output the cellarray after the parfor loop into the file.
Titus

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by