Skip to content

Commit 768819c

Browse files
authored
Fix data race in the example
We have a data race on the shared variable `sum` (involving unsynchronized modification `+=`) in `long_computation_omp2`. Fix: - `default(none)` - prevents inadvertent data races (`nb` was another potential one when not `const`; adjusted) - `reduction(+ : sum)` - treats `sum` as a reduction variable (with proper synchronization)
1 parent 810b0f9 commit 768819c

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

src/2013-05-16-using-rcppprogress.Rmd

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,14 +170,14 @@ Now check that it is parallelized:
170170
// [[Rcpp::depends(RcppProgress)]]
171171
#include <progress.hpp>
172172
// [[Rcpp::export]]
173-
double long_computation_omp2(int nb, int threads=1) {
173+
double long_computation_omp2(const int nb, int threads=1) {
174174
#ifdef _OPENMP
175175
if ( threads > 0 )
176176
omp_set_num_threads( threads );
177177
#endif
178178
Progress p(nb, true);
179179
double sum = 0;
180-
#pragma omp parallel for schedule(dynamic)
180+
#pragma omp parallel for default(none) reduction(+ : sum) schedule(dynamic)
181181
for (int i = 0; i < nb; ++i) {
182182
double thread_sum = 0;
183183
if ( ! Progress::check_abort() ) {

0 commit comments

Comments
 (0)