RcppCore / RcppParallel

High-level functions for parallel programming with Rcpp
http://rcppcore.github.io/RcppParallel/
170 stars 58 forks source link

Thread-safe versions to check for NA #96

Closed asardaes closed 5 years ago

asardaes commented 5 years ago

My Google search led me to contradicting answers. Is it possible to use the Rcpp versions of is_na inside threads? Even if it is, would there be a faster way to check for NA?

eddelbuettel commented 5 years ago

a) What type? double aka numeric? C++ has you covered. b) Other types? See the R sources and cover the bit pattern to a header of your choice. This should allow the comparison without requiring R iself and any and all gc events.

eddelbuettel commented 5 years ago

I.e. what I meant what something along these lines (turn C++11 on if needed, my compiler has it by default)

R> Rcpp::cppFunction("bool myCheck(const double x) { return std::isfinite(x); }")
R> myCheck(NA)
[1] FALSE
R> myCheck(NaN)
[1] FALSE
R> myCheck(Inf)
[1] FALSE
R> myCheck(1L)
[1] TRUE
R> 

You can also check for just NaN which, if memory serves, also catches the NA R uses but I am a little rusty on the details -- they may be identical apart from a high bit or some other cleverness.

asardaes commented 5 years ago

Ideally I'd like to use something that covers all types of NA that R uses.

In this answer it was suggested to use something like the following to compare bit patterns

int nb_na7( const NumericVector& x){
  const long long* p = reinterpret_cast<const long long*>(x.begin()) ;
  long long na = *reinterpret_cast<long long*>(&NA_REAL) ;

  return std::count(p, p + x.size(), na ) ;
}

but someone mentioned some parts would "violate C++ strict aliasing rules and are therefore invalid C++".

kevinushey commented 5 years ago

Note that R's NA is a specific type of IEE 754 NaN; checking for that specific bit-pattern may or may not be what you want.

All that said the various R APIs here should be safe as they do not allocate or touch the R garbage collector or other R global variables.

asardaes commented 5 years ago

Thanks, everyone. I have been doing some limited tests with Rcpp::Vector<RTYPE>::is_na and haven't run into problems.