BerriJ
BerriJ

Reputation: 1019

Why does rcpp::warning() not work within openmp loop

Consider the following reprex:

//test.cpp
#include <Rcpp.h>

// [[Rcpp::plugins(openmp)]]
using namespace Rcpp;

#ifdef _OPENMP
#include <omp.h>
#endif

//[[Rcpp::export]]
void example_rcpp_warning(int N)
{
  NumericMatrix mat(N, 2);
#pragma omp parallel for
  for (int i = 0; i < N; i++)
  {
#pragma omp critical
    Rcpp::warning(std::to_string(omp_get_thread_num()));
  }
}

//[[Rcpp::export]]
void example_cout(int N)
{
  NumericMatrix mat(N, 2);
#pragma omp parallel for
  for (int i = 0; i < N; i++)
  {
#pragma omp critical
    std::cout << "Thread: " << omp_get_thread_num() << std::endl;
  }
}

This can be compiled and run using Rcpp:

#test.R
Rcpp::sourceCpp("test.cpp")
example_cout(3)
example_rcpp_warning(3)

This leads to the following output:

[R] Rcpp::sourceCpp("test.cpp")
[R] example_cout(3)
Thread: 0
Thread: 2
Thread: 1
[R] example_rcpp_warning(3)

So, example_cout() produces the desired output. But example_rcpp_warning keeps my console busy but never finished, nor does it print the warnings.

Note that "#pragma omp critical" is not necessary but ensures that the output is written line by line.

Upvotes: 1

Views: 47

Answers (1)

BerriJ
BerriJ

Reputation: 1019

Thanks to Ahmed AEK who reffered me to this [source][1].

Calling multi-threaded C++ code from R has its perils. Since the R interpreter is single-threaded, one must not check for user interruptions or print to the R console from multiple threads

This answers my question. [1]: https://cran.r-project.org/web/packages/RcppThread/vignettes/RcppThread-vignette.pdf

Upvotes: 0

Related Questions