I wonder in OpenMP, do I need to flush a shared variable to be updated in a critical region before it is actually updated?
For example, I would like to calculate the maximum value in a vector with the code below:
int max = vec[0];
#pragma omp parallel
{
int local_max = vec[0];
#pragma omp for
for (uint i = 0; i < vec.size(); i++) {
if (vec[i] > local_max) local_max = vec[i];
}
#pragma omp critical
{
if (local_max > max) max = local_max;
}
}
I wonder if I need to first flush the variables after entering the critical section, since it is likely that one thread gets a stale view of variable "max" and updated it into a value that is smaller than the true max but larger than the stale max.
You do not need a flush when entering a critical region - there already is an implicit flush when entering and exiting a critical region.
Note: For your example case, it is recommended to use a reduction
clause - which basically does what you do but is more concise.
Also it is possible for an implementation to compute the values in O(log(n))
instead of O(n)
time.