Choosing The Right Parallel Loop

From CSE231 Wiki
Revision as of 17:09, 9 February 2024 by Cosgroved (talk | contribs)
Jump to navigation Jump to search

Java has multiple looping options. There is a while loop, a do/while loop, and the two for loops. Here we will focus on just the two for loop variations.

There is the old school for loop which is often used to :

String[] names = { "fred", "george" };
for(int i=0; i<names.length; ++i) {
    String name = names[i];
    process(name);
}

And the for each loop:

String[] names = { "fred", "george" };
for(String name : names) {
    process(name);
}

While it is not always the right tool for the job (for example, when you need to initialize the values in an array), the for each loop is arguably superior when you can use it.

The parallel library provided in CSE 231s supports both forms of parallel loops- ones which create a task per index:

String[] names = { "fred", "george" };
join_void_fork_loop(0, names.length, (i) -> {
    String name = names[i];
    process(name);
});

and ones which operate more like a for each loop:

String[] names = { "fred", "george" };
join_void_fork_loop(names, (name) -> {
    process(name);
});

Much like the sequential loops provided by Java, it is often superior to use the for each style of the parallel loop (when you can).

Sometimes, the tests even enforce you to use this more appropriate version of the loop simply because it is better style.