Site Tools


openmp

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
openmp [June 10, 2026 at 21:21] – created Ivan Janevskiopenmp [August 22, 2026 at 15:22] (current) – external edit 127.0.0.1
Line 1: Line 1:
 # OpenMP # OpenMP
-**OpenMP** is a standardized API for+ 
 +**OpenMP** is a shared-memory parallelism API for C, C++, and Fortran. Add a `#pragma omp` directive before a loop or block to parallelize it across available cores. The compiler handles thread creation and synchronization; if it doesn't support OpenMP, directives are silently ignored and the program runs serially, making debugging easy. 
 + 
 +The execution model is **fork-join**: a single thread forks into a worker team at `#pragma omp parallel`, they execute concurrently, then join back. Thread count defaults to the number of logical cores, configurable via `OMP_NUM_THREADS=N` at runtime or `omp_set_num_threads(n)` in code. Compile with `-fopenmp` and include `<omp.h>` for the `omp_*` runtime functions.
  
 ```c ```c
-// Compile: gcc -fopenmp main.c -o main +// compile: gcc -O2 -fopenmp -o sum sum.c 
-// Run    ./main+// runOMP_NUM_THREADS=4 ./sum 
 +// description: parallel reduction using a single pragma 
 + 
 +#include <omp.h>
 #include <stdio.h> #include <stdio.h>
  
-int main() { +int main(void) { 
-    +    long n = 1000000000L, sum = 0; 
 +    double t = omp_get_wtime(); 
 +    #pragma omp parallel for reduction(+:sum) 
 +    for (long i = 0; i < n; i++) 
 +        sum += i; 
 +    printf("sum=%ld  time=%.2fs\n", sum, omp_get_wtime() - t); 
 +    return 0;
 } }
 ``` ```
 +
 +On a 4-core machine this runs roughly 4× faster with `-fopenmp` than without. [[amdahls-law|Amdahl's law]] limits speedup when part of the program is inherently serial; reducing overhead like false sharing and load imbalance matters more than just adding threads.
 +
 +## Concepts
 +
 + 1. [[openmp-data-sharing|Data sharing]]
 + 2. [[openmp-parallel-loops|Parallel loops]]
 + 3. [[openmp-collapse|Collapse]]
 + 4. [[openmp-reduction|Reduction]]
 + 5. [[openmp-scheduling|Scheduling]]
 + 6. [[openmp-simd|SIMD]]
 + 7. [[openmp-tasks|Tasks]]
 + 8. [[openmp-single|Single]]
 + 9. [[openmp-master|Master]]
 + 10. [[openmp-sections|Sections]]
 + 11. [[openmp-barrier|Barrier]]
 + 12. [[openmp-nowait|Nowait]]
 + 13. [[openmp-critical-sections|Critical sections]]
 + 14. [[openmp-atomic|Atomic]]
 + 15. [[openmp-flush|Flush]]
 + 16. [[openmp-false-sharing|False sharing]]
 + 17. [[openmp-thread-affinity|Thread affinity]]
 + 18. [[openmp-time-measurement|Time measurement]]
 + 19. [[openmp-overview|Overview]]
 +
openmp.1781126467.md.gz · Last modified: by Ivan Janevski