data-sharing-openmp
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| data-sharing-openmp [June 11, 2026 at 09:19] โ created - external edit 127.0.0.1 | data-sharing-openmp [Unknown date] (current) โ removed - external edit (Unknown date) 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | # Data sharing (OpenMP) | ||
| - | A local variable in a C function lives on the stack and is private to that call. When multiple threads run the same code, each gets its own stack, so locals are naturally separate. Variables declared *outside* a parallel region are different: all threads share the same memory location. **Data sharing** in OpenMP makes this explicit. Every variable accessed inside a parallel region is either **shared** (all threads read and write the same location) or **private** (each thread gets its own copy). The default for variables declared outside the region is `shared`, which silently causes a race condition if threads write to them: | ||
| - | |||
| - | ```c | ||
| - | int x = 0; | ||
| - | #pragma omp parallel | ||
| - | x = omp_get_thread_num(); | ||
| - | ``` | ||
| - | |||
| - | The `private`, `firstprivate`, | ||
| - | |||
| - | ```c | ||
| - | int x = 42; | ||
| - | |||
| - | #pragma omp parallel private(x) | ||
| - | { | ||
| - | x = omp_get_thread_num(); | ||
| - | printf(" | ||
| - | } | ||
| - | // x is still 42 here; private copies do not write back | ||
| - | ``` | ||
| - | |||
| - | `firstprivate(x)` is like `private` but initialises each thread' | ||
data-sharing-openmp.1781169594.md.gz ยท Last modified: by 127.0.0.1
