How to make variables in order when using parfor?

4 views (last 30 days)
Hello. I am now using parfor and have some problems.
For example, When I run this simple code:
k=10;
parfor n = 1:k
disp(['Time Step = ',num2str(n)]);
end
the results are:
Time Step = 1
Time Step = 2
Time Step = 3
Time Step = 8
Time Step = 7
Time Step = 4
Time Step = 5
Time Step = 6
Time Step = 10
Time Step = 9
but I want to get the results in a row like:
Time Step = 1
Time Step = 2
Time Step = 3
Time Step = 4
Time Step = 5
Time Step = 6
Time Step = 7
Time Step = 8
Time Step = 9
Time Step = 10
So, how to make variables in order when using parfor?
Thanks.
  5 Comments
Walter Roberson
Walter Roberson on 14 Dec 2021
Use a controlling process that reads frames from the video file. As each one is read, parfeval() the processing function, passing in the content of the frame. As of R2021b this can be done with background threads with basic MATLAB
Mike Croucher
Mike Croucher on 14 Dec 2021
@Arthur Vieira Enforcing order almost guarantees serial execution which also outweighs the benefits of parfor. There would need to be a lot of blocking going on. This isn't an issue particular to parfor, its an issue related to parallel looping in general.
In your case, I would investigate alternative and more advanced ways of exposing the parallelism rather than a simple parfor loop. For example, could you decompress the frames in batches? Maybe at the moment you have a loop that looks like this (in pseudo-code)
loop over all frames % each core does iterations of this independently
decompress a frame
process it
end loop
Instead maybe something do something like
chunksize=32 frames
loop over all chunks
decompress a chunk of frames
loop over frames in a chunk
process frame
endloop
endloop
Depending on the timings of the various operations, parallelising over either loop may be an option. You could also vary the chunk size.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!