Tutorial - Parallel Constructs
Introduction
In this tutorial we shall look at more advanced parallel constructs as to what were discussed in the Hello world tutorial. There will also be some reference made to the concepts noted in the functions and simple types tutorials too.
Parallel composition
In the Hello world tutorial we briefly saw an example of using parallel composition (||) to control parallelism. Let's now further explore this with some code examples:
#include <io> #include <string> #include <parallel> function void main() { { var i:=pid(); print("Hello from PID "+itostring(i)+"\n"); } || { var i:=30; var f:=20; print("Addition result is "+itostring(i+f)+"\n"); }; };
Which specifies two blocks of code, both running in parallel (two processes), the first will display a message with the process ID in it, the other process will declare two Int variables and display the result of adding these together. This approach; of specifying code in blocks and then using parallel composition to run the blocks in parallel, on different processes, is a useful one. As a further exercise try rearranging the blocks and view the value of the process ID reported, also add further parallel blocks (via more parallel composition) to do things and look at the results.
Unstructured parallel composition
In the previous example we structured parallel composition by using blocks, it is also possible to run statements in parallel using this composition, although it is important to understand the associativity and precedence of parallel composition and sequential composition when doing so.
#include <io> #include <string> #include <parallel> function void main() { var i:=0; var j:=0; var z:=0; var m:=0; var n:=0; var t:=0; {i:=1;j:=1||z:=1;m:=1||n:=1||t:=1;}; print(itostring(pid())+":: i: "+itostring(i)+", j: "+itostring(j)+", z: "+itostring(z) +", m: "+itostring(m)+", n: "+itostring(n)+", t: "+itostring(t)+"\n"); };