0

I have found a strange problem when using Rcpp, maybe it is a known limitation in Rcpp package, but I failed to find any hints by searching related documents, hope someone can help or explain this problem.

Here is my code:

// [[Rcpp::export]]
void set_r_cb(Function f) {
  Environment env = Environment::global_env();
  env["place_f"] = f;
}
void __test_thread(void* data) {
  Rprintf("in thread body\n");
  Function f("place_f");
  f(*((NumericVector*)data));
}

// [[Rcpp::export]]
NumericVector use_r_callback(NumericVector x) {
  Environment env = Environment::global_env();
  Function f = env["place_f"];
{  // test thread 
  tthread::thread t(__test_thread, x);
  t.join();
}  
  return f(x);
}

where in R code:

> x = runif(100)
> set_r_cb(fivenum)

when there is no thread call, everything is OK. return something like this:

> use_r_callback(x)
[1] 0.01825808 0.24010829 0.37492796 0.58618216 0.93935818

when using thread code,I got such error:

> use_r_callback(x)
in thread body
Error: C stack usage  237426928 is too close to the limit

BTW, I use tinythread, https://gitorious.org/tinythread, but same error occurs when use boost::thread.

1 Answer 1

6

R itself is single-treaded so you simply cannot use your R instance from multiple threads.

You can call C++ from R which

  • sets things up (if needed)
  • sets a mutex
  • multithreads to its heart's content, never calling R, never touching R datastructures (and here you can use Open MP, Boost threads, C++ threads, standard pthreads, ...)
  • collects results
  • clears the mutex
  • prepares return (if needed)

and returns. Pretty much everything else will get you errors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.