Flush is OpenMP's mechanism for enforcing memory visibility across threads by committing all pending writes to shared memory and invalidating locally cached reads, making the calling thread's view consistent with every other thread. Like C's volatile keyword, it prevents the compiler and CPU from keeping shared variables in registers or store-buffers so that one thread's writes become visible to another. 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.