Consider the following sequential function. When I parallelize my code, each thread will call this function from a parallel area (not shown). I am trying to make this thread safe and efficient (fast).
float get_stored_value__or__calculate_if_does_not_yet_exist( int A )
{
static std::map<int, float> my_map;
std::map::iterator it_find = my_map.find(A);
bool found_A = it_find != my_map.end();
if (found_A)
{
return it_find->second;
}
else
{
float result_for_A = calculate_value(A);
my_map[A] = result_for_A;
return result_for_A;
}
}
Almost every time this function is called, threads will successfully "find" the stored value for their "A" (regardless of what it is). From time to time, when "new A" is called, the value must be calculated and stored.
So where should I put #pragma omp critical?
Although it is easy, it is very difficult to put a #pragma omp criticalaround it all, as each thread will do it constantly, and it will often be read-only.
"" critical "" lock? "" my_map else. .find .
, .
.