Site Tools


data-sharing-openmp

Differences

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

Link to this comparison view

Next revision
Previous revision
data-sharing-openmp [June 11, 2026 at 09:19] โ€“ created - external edit 127.0.0.1data-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();   // all threads write to the same x โ€” race condition 
-``` 
- 
-The `private`, `firstprivate`, and `lastprivate` clauses override this per variable. 
- 
-```c 
-int x = 42; 
- 
-#pragma omp parallel private(x) 
-{ 
-    x = omp_get_thread_num();  // each thread's x is independent, starts uninitialised 
-    printf("%d\n", x); 
-} 
-// x is still 42 here; private copies do not write back 
-``` 
- 
-`firstprivate(x)` is like `private` but initialises each thread's copy to the value `x` held before the region. `lastprivate(x)` writes back the value from the logically last iteration to the original variable after the region, which is useful when a loop computes something that should persist. A good habit is to add `default(none)` to any parallel region, which forces every variable to be classified explicitly and turns accidental sharing into a compile error. 
  
data-sharing-openmp.1781169594.md.gz ยท Last modified: by 127.0.0.1