# Shared-Memory Programming with OpenMP ::::::{tab-set} :sync-group: lang :class: lang-tabs :::::{tab-item} En :sync: en OpenMP is a method of parallel programming for the case where several processors are attached to a shared memory. The main advantage of such programming is a *single* address space across the entire memory system - each processor can read and write all memory locations - one logical memory space - all processors address memory with the same address ![](../files/u3/OpenMP-true.png) The problem with OpenMP is that the ideal structure is not possible in larger systems, and there is usually the following form with a hierarchical connection of processors and memory via a fast network. ![](../files/u3/OpenMP-distributed.png) Communication can be problematic, so it is important how the intermediate and local memory (cache) is used. Shared-memory programming (*shared memory*) is simple. In standardisation, OpenMP has become the most established; it manages threads by means of preprocessor directives, written as a directive that is normally not compiled - Fortran: ``` fortran !$OMP (ali C$OMP ali *$OMP za F77) ``` - C/C++: ``` c #pragma omp ``` The basis of parallel programming is the *parallel* region, which defines a section of the program. ## Shared and private data - Within a *parallel* region, variables can be shared or private - All threads see the same copy of shared variables - All threads can read or write shared variables - Each thread has its own copy of private variables. These are invisible to other threads - A private variable can be read or written only in the thread that owns it - Private variables have no initial value and must be initialised at the start of the parallel region - Shared variables that are used only for reading can be freely used in all parallel regions ``` fortran do i = 1, 100 a(i) = a(i) + b(i) end do ``` OpenMP takes care of synchronising the writing and reading of shared variables. If synchronisation blocks the computation of threads, it is better to use partial computation that is combined at the end by a reduction into a single variable, which is useful for many arithmetic operations. The following example is suitable for reduction ``` c b = 0; for (i=0; i++; i ``` fortran do i = 1, 100 a(i) = a(i) + b(i) end do ``` Za sinhronizacijo pisanja in branja deljenih spremenljivk skrbi OpenMP. Če sinhronizacija blokira računanje niti je bolje uporabiti delno izračunavanje, ki se združi na koncu z redukcijo v eno samo spremenljivko, kar je uporabno za veliko računskih operacij. Naslednji primer je primeren za redukcijo ``` c b = 0; for (i=0; i++; i