Skip to content

How to safely using OpenMP pragma inside a .C() function?

1 message · Martin Morgan

#
On 08/29/2011 05:36 PM, Simon Urbanek wrote:
Hi Simon et al.,

I'm trying to resolve this dictum (no R API calls) with my understanding 
of OpenMP's shared memory model. For instance I would have thought R API 
calls inside critical sections would be safe, as this (though obviously 
gratuitous) appears to be on my own machine (which I know is no way to 
arrive at a general understanding!)

#include <omp.h>
#include <Rdefines.h>

SEXP omp()
{
     const int n = 40;
     SEXP res = PROTECT(allocVector(INTSXP, n));
     const int it = 1000;
     int j;
     for (j = 0; j < Rf_length(res); ++j)
         INTEGER(res)[j] = 0;

     omp_set_num_threads(n);
     j = 0;
#pragma omp parallel for
     for (int i = 0; i < it; ++i)
#pragma omp critical
     {
         j  = omp_get_thread_num();
         SEXP elt = PROTECT(Rf_ScalarInteger(1));
         INTEGER(res)[j] = INTEGER(res)[j] + INTEGER(elt)[0];
         UNPROTECT(1);
     }

     UNPROTECT(1);
     return res;
}

and

 > dyn.load("omp.so"); table(x <- .Call("omp"))

25
40


?

Martin

 > sessionInfo()
R Under development (unstable) (2011-09-12 r56997)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
  [7] LC_PAPER=C                 LC_NAME=C
  [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  utils     datasets  grDevices methods   base

loaded via a namespace (and not attached):
[1] tools_2.14.0
Sent from the R devel mailing list archive at Nabble.com.