Site Tools


flush-openmp

Differences

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

Link to this comparison view

Next revision
Previous revision
flush-openmp [June 11, 2026 at 09:19] – created - external edit 127.0.0.1flush-openmp [Unknown date] (current) – removed - external edit (Unknown date) 127.0.0.1
Line 1: Line 1:
-# Flush (OpenMP) 
-C's `volatile` keyword tells the compiler that a variable can change outside normal program flow and must not be cached in a register: every read goes to memory and every write is committed immediately. OpenMP threads face a similar problem at a larger scale: the compiler and CPU are free to keep shared variables in registers or store-buffers, so one thread's writes may not be visible to another without explicit synchronisation. **Flush** is OpenMP's mechanism for enforcing that visibility: it commits all pending writes to shared memory and invalidates locally cached reads, making the calling thread's view consistent with every other thread. Barriers, critical sections, and atomics all imply a flush, so the directive is only needed when synchronising through a bare shared variable with no other construct present. 
- 
-```c 
-int ready = 0; 
- 
-// thread 0: produce data, then signal 
-do_work(); 
-#pragma omp flush           // ensure do_work() writes are visible before setting ready 
-ready = 1; 
-#pragma omp flush(ready)    // flush the flag itself 
- 
-// thread 1: spin until signalled 
-while (!ready) { 
-    #pragma omp flush(ready)    // re-read ready from memory on each iteration 
-} 
-use_result(); 
-``` 
- 
-This spin-wait pattern is fragile and almost always better replaced with a barrier or an `atomic` write/read pair. `flush` is a low-level escape hatch for lock-free patterns where no higher-level construct fits. 
  
flush-openmp.1781169574.md.gz · Last modified: by 127.0.0.1