c++ - OpenMP: how to handle race condition on global std vectors -
i'm interested in parallelize loop using openmp global std vectors involved.
in specific example, order in operation vec[1] = vec[1] + i
executed doesn't matter results appears wrong due race conditions. proper way handle this?
the reduction clause seems not working containers.
#include <iostream> #include <vector> std::vector<double> vec = {1,1}; void func(int i){ vec[1] = vec[1] + i; } int main(int argc, char *argv[]) { int k; #pragma omp parallel for(k=1; k<10; k++){ func(k); } std::cout << vec[0] << ", " << vec[1] << std::endl; }
the problem line
vec[1] = vec[1] + i;
isn't atomic. when compiled, looks more this
auto tmp = vec[1]; tmp = tmp + i; vec[1] = tmp
and in case, have race condition.
if want way, can tell openmp vec[1] = vec[1] + i;
should atomic, :
#include <iostream> #include <vector> std::vector<double> vec = {1,1}; void func(int i){ #pragma omp atomic vec[1] = vec[1] + 1; } int main(int argc, char *argv[]) { int k; #pragma omp parallel for(k=1; k<100; k++){ func(k); } std::cout << vec[0] << ", " << vec[1] << std::endl; }
Comments
Post a Comment