**This is an old revision of the document!**
Table of Contents
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.
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.
