# OpenMP **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 `` for the `omp_*` runtime functions. ```c // compile: gcc -O2 -fopenmp -o sum sum.c // run: OMP_NUM_THREADS=4 ./sum // description: parallel reduction using a single pragma #include #include 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]]