openmp basics

**OpenMP** — a directive-based API for shared-memory parallel programming in C/C++/Fortran, enabling parallelization with minimal code changes. **Basic Usage** ```c #pragma omp parallel for for (int i = 0; i < N; i++) { result[i] = compute(data[i]); } ``` One line added → loop runs on all available cores. **Key Directives** - `#pragma omp parallel` — create a team of threads - `#pragma omp for` — distribute loop iterations among threads - `#pragma omp critical` — mutual exclusion for a code block - `#pragma omp atomic` — atomic update of a single variable - `#pragma omp barrier` — synchronization point - `#pragma omp task` — create a task for dynamic parallelism **Data Sharing** - `shared(var)` — all threads see the same variable (default for most) - `private(var)` — each thread gets its own copy - `reduction(+:sum)` — each thread has private copy, combined at end - `firstprivate` / `lastprivate` — control initialization and final value **Scheduling** - `schedule(static)` — divide iterations equally upfront - `schedule(dynamic)` — threads grab chunks from a queue - `schedule(guided)` — decreasing chunk sizes (good for imbalanced workloads) **OpenMP** is the easiest way to parallelize existing serial code — 80% of the benefit with 20% of the effort compared to manual threading.

Go deeper with CFSGPT

Get AI-powered deep-dives, save terms, and run advanced simulations — free account.

Create Free Account