# A Short Introduction to Parallel Programming ::::::{tab-set} :sync-group: lang :class: lang-tabs :::::{tab-item} En :sync: en Two approaches are used for programming parallel tasks: 1. MPI (Message Passing Interface) 2. OpenMP (Open Multi Processing) The basic rule of parallel programming is that the result of the serial and the parallel program must be the same. With OpenMP this is very easy to verify. Problems can arise only with programs that use a random number generator (Monte Carlo methods). ## OpenMP OpenMP programs run on a single node only, split into several parallel threads. The compiler itself takes care of creating the threads. How the program should be split into threads is written in program comments. This means that the parallel program is no different from the serial one. The program can even be tested by first compiling it without OpenMP, which gives a serial program, and then compiling it with OpenMP, which gives a parallel program that runs simultaneously on several cores of one node. The parallel threads of an OpenMP program have shared variables which they must access in a coordinated way to avoid problems with simultaneous reading and writing of the same variable. The compiler takes care of setting up *semaphores*, but shared variables where such a problem may occur must be declared to the compiler. It is best for parallel programs to have as few shared variables (***shared***) as possible, or for the variables to be independent (***private***). If the result of several parallel parts is a single number that contributes to the result (a functional), it is better to combine the partial results at the end rather than along the way. Such an operation, which is fairly common (piecewise integration, summation), is called a **reduction**. The advantage of shared-memory programs (*Shared Memory Programming -* SMP) is precisely fast access to data, since unlike MPI it does not have to be transferred over the network. The drawback of OpenMP is the limit on the number of processors, since programs as a rule run on a single node only, so the program is limited to a maximum of 16 processor cores. Extensions to more cores are made possible by special solutions such as GPU (*Graphics Processor Unit)*, the best known of which is CUDA. Some compilers also provide so-called ClusterMP, which equips an OpenMP program at the preprocessor level with MPI for communication between nodes. ## Example of parallelization with OpenMP The following example computes the area of the unit circle by integration in a loop. ``` text #include #include #define N 100000 int main() { double area = 0.0; #pragma omp parallel for reduction(+:area) for(int i = 0; i < N; i++) { double x = (i+0.5)/N; area += sqrt(1.0 - x*x); } printf("Površina : %g\n", 4.0*area/N); return 0; } ``` The program is compiled with cc -std=c99 -o pi-openmp -fopenmp -O2 pi-omp.c -lm It can also be compiled without the OpenMP directive, which gives a serial program. With the `#pragma` comment we instruct the compiler to split the loop across all available processors, each of which computes only part of the intervals in several threads. The compiler takes care of the correct distribution of loop intervals among threads. An OpenMP program that is started runs in a single process only. After the loop finishes, the partial sums *area* are added together by reduction and the result 3.14159 is printed. The program can be run on a node with the command: ``` text srun --partition=rome --nodes=1 --ntasks=1 --cpus-per-task=12 ./pi-openmp ``` The result is printed to the terminal. To reserve a whole node for the run, use ``` text srun --partition=rome --nodes=1 --exclusive ./pi-openmp ``` ## MPI Unlike OpenMP, the parallel parts of an MPI program are independent processes that do not share memory. With MPI there can therefore be no problems with simultaneous access to variables, since all variables are owned by the processes in separate memories. For shared variables, sending data over the network layer must be programmed with the MPI library. This way of communicating also applies to several processes on the same node, but communication between processes on one node is faster than between processes on different nodes. MPI programs are not limited in the number of parallel processes. The limit may be the application itself through the amount of communication. For good performance of MPI programs it is therefore necessary to provide the fastest possible network between nodes (e.g. with Infiniband), or to design the program so that communication does not become a bottleneck as the number of processes grows. To reduce communication and thus speed things up, a combination of MPI and OpenMP can also be used. MPI handles communication between nodes, and OpenMP communication within a node. In principle such a solution is the best, but newer multi-core processors also allow a smaller number of cores to run even [faster than the base frequency](http://www.intel.com/technology/turboboost "Turbo Boost") at the expense of the other cores. ## Example of parallelization with MPI The area computation is split across several processes. With OpenMP the compiler took care of the correct distribution of the counter *i* among loop threads. With MPI it is the programmer's responsibility to distribute tasks among processes. When the program starts, the requested number of identical programs is created and each runs on its own processor. The process number and the total number of processes are obtained with the appropriate MPI\_ function calls. In the following example the loop is split using the *leapfrog* method, which allows an even distribution of an integer interval over any number of processes. ``` text #include #include #include #define N 100000 int main(int argc, char *argv[]) { int id; // številka procesa int procesov; // število vseh procesov double area = 0.0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &procesov); for(int i = id; i < N; i += procesov) { double x = (i+0.5)/N; area += sqrt(1.0 - x*x); } double skupno; MPI_Reduce(&area, &skupno, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (id == 0) printf("Površina : %g\n", 4.0*skupno/N); MPI_Finalize(); return 0; } ``` The program is compiled and run on 48 processes with the commands ``` text module load openmpi mpicc -std=c99 -o pi-mpi pi-mpi.c srun --partition=rome --ntasks=48 --ntasks-per-core=1 ./pi-mpi ``` The result is printed to the terminal. ::::: :::::{tab-item} Slo :sync: sl **Kratek uvod v vzporedno programiranje** Za programiranje vzporednih nalog uporabljamo dva načina: 1. MPI (Message Passing Interface) 2. OpenMP (Open Multi Processing) Osnovno pravilo vzporednega programiranja je, da mora biti rezultat zaporednega in vzporednega programa enak. Z OpenMP je to zelo enstavno preverljivo. Težave lahko nastopijo le pri programih, ki uporabljajo generator naključnih števil (Monte Carlo metode). ## OpenMP OpenMP programi se izvajajo le na enem vozlišču z porazdelitvijo na več vzporednih niti (threads). Za izdelavo niti skrbi prevajalnik sam. Kako naj se program razdeli na več niti se napiše v komentarje programa. To pa pomeni, da vzporedni program ni nič drugačen od zaporednega. Program lahko celo testiramo tako, da ga enkrat prevedemo brez OpenMP in dobimo zaporeden program. Nato pa ga prevedemo še z OpenMP in dobimo vzporeden program, ki se hkrati izvaja na večih jedrih enega vozlišča. Vzporedne niti OpenMP programa imajo skupne spremenljivke do katerih morajo usklajeno dostopati da ne pride do težav s hkratnim branjem in pisanjem iste spremenljivke. Za postavitev *semaforjev* skrbi prevajalnik sam, vendar je potrebno skupne spremenljivke pri katerih lahko pride do takšne težave prijaviti prevajalniku. Najbolje za vzporedne programe je, da imajo čim manj skupnih spremenljivk (***shared***) ali pa da so spremenljivke neodvisne (***private***) . Če se je rezultat večih vzporednih delov ena sama številka, ki prispeva k rezultatu (funkcional) je bolje, da se delni rezultati poračunajo na koncu in ne sproti. Taki operaciji, ki je dokaj pogosta (integriranje po delih, sumacija) pravimo **redukcija**. Prednost programov z deljenim spominom (*Shared Memory Programming -* SMP) je prav v hitrem dostopu do podatkov, saj jih ni potrebno tako kot pri MPI prenašati preko mrežnega dela. Slabost OpenMP pa je v omejitvi števila procesorjev saj programi praviloma delujejo le na enem vozlišču in je tako program omejen na max 16 procesorskih jeder. Razširitve na več jeder omogočajo posebne rešitve kot je npr GPU  (*Graphics Processor Unit)* od katerih je najbolj znana CUDA. Nekateri prevajalniki omogočajo tudi tako imenovani ClusterMP, ki OpenMP program na nivoju predprocesorja opremijo z MPI za komunikacijo med vozliči. ## Primer paralelizacije z OpenMP Naslednji primer v katerem računamo površino enotskega kroga z integracijo v zanki. ``` text #include #include #define N 100000 int main() { double area = 0.0; #pragma omp parallel for reduction(+:area) for(int i = 0; i < N; i++) { double x = (i+0.5)/N; area += sqrt(1.0 - x*x); } printf("Površina : %g\n", 4.0*area/N); return 0; } ``` Program prevedemo z cc -std=c99 -o pi-openmp -fopenmp -O2 pi-omp.c -lm Lahko pa ga prededemo tudi brez OpenMP direktive in tako dobimo zaporeden program. S `#pragma` komentarjem prevajalniku ukažemo, da razdeli zanko na vse razpoložljive procesorje, ki v večih nitih vsak izračuna le del intervalov. Za pravilno razdelitev intervalov zanke na niti skrbi prevajalnik. OpenMP program, ki se zažene se izvaja le v enem procesu. Po končani zanki se z redukcijo seštejejo delne vsote *area* in izpiše rezultat 3.14159 Zagon programa lahko izvedemo na vozlišču z ukazom: ``` text srun --partition=rome --nodes=1 --ntasks=1 --cpus-per-task=12 ./pi-openmp ``` Rezultat se izpiše v terminal. Če želimo za izvajanje rezervirati celotno vozlišče, uporabimo ukaz ``` text srun --partition=rome --nodes=1 --exclusive ./pi-openmp ``` ## MPI Za razliko od OpenMP so vzporedni deli MPI programa samostojni procesi, ki si med sabo ne delijo spomina. Tako pri MPI ne more priti do težav s hkratnim dostopanjem do spremenljivk, saj so vse spremenljivke v ločenih spominih lastni procesom. Za skupne spremenljivke je potrebno sprogramirati s knjižnico MPI pošiljanje podatkov preko mrežnega sloja. Tak način komuniciranja velja tudi za več procesov na istem vozlišču, vendar je hitrost komunikacije hitrejša med procesi enega vozlišča, kot pa med procesi različnih vozlišč. Programi MPI niso omejeni po številu vzporednih procesov. Omejitev lahko predstavlja aplikacija sama s količino komunikacije. Zato je potrebno za dobro delovanje MPI programov zagotoviti čim hitrejšo mrežo med vozlišči (npr z Infinibandom) ali pa program izdelati tako, da komunikacija ne predstavlja ozkega grla ob večanju števila procesov. Za zmanjšanje komunikacije in s tem pohitritev lahko uporabimo tudi kombinacijo MPI in OpenMP. MPI skrbi za komunikacijo med vozlišči, OpenMP pa za komunikacijo v vozlišču. Načeloma je takšna rešitev najboljša, vendar pa v novejših jedernih procesorjih obstaja tudi možnost, da lahko manjše število jeder deluje celo [hitreje od osnovne frekvence](http://www.intel.com/technology/turboboost "Turbo Boost") na račun ostalih jeder. ## Primer paralelizacije z MPI Računanje površine razdelimo na  več procesov. Pri OpenMP je za pravilno razdelitev števca *i* na niti zanke skrbel prevajalnik. Pri MPI pa odgovornost programerja, da razdeli naloge na procese. Ob zagonu programa se naredi zahtevano število istih programom in vsak teče na svojem procesorju. Številko procesa in skupno število procesov se pridobi z ustreznim klicem MPI\_ funkcij. V naslednjem primeru se je zanka razdelila z metodo *leapfrog*, ki omogoča enakomerno razporeditev celoštevilčnega intervala na poljubno število procesov. ``` text #include #include #include #define N 100000 int main(int argc, char *argv[]) { int id; // številka procesa int procesov; // število vseh procesov double area = 0.0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &procesov); for(int i = id; i < N; i += procesov) { double x = (i+0.5)/N; area += sqrt(1.0 - x*x); } double skupno; MPI_Reduce(&area, &skupno, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (id == 0) printf("Površina : %g\n", 4.0*skupno/N); MPI_Finalize(); return 0; } ``` Program prevedemo z in poženemo na 48 procesih z ukazi ``` text module load openmpi mpicc -std=c99 -o pi-mpi pi-mpi.c srun --partition=rome --ntasks=48 --ntasks-per-core=1 ./pi-mpi ``` Rezultat se izpiše v terminal. ::::: ::::::