使用 Rcpp 时抛出错误的线程安全方法是什么

What is a thread safe way to throw an error while using Rcpp

我在 Rcpp 函数中使用 RcppThread 进行并行处理。在并行循环中间抛出错误的首选方法是什么? R 的 API 是单线程的,所以我假设 Rcpp::stop() 不是线程安全的。 RcppThread 提供线程安全 coutCheckUserInterrupt 的方法,但据我所知,线程安全 stop.

不是

我正在尝试做的一个例子:

#include <RcppThread.h>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppThread)]]

void myfun() {

  // parallel loop
  RcppThread::parallelFor(0, 100, [](int j){
    // do something that causes an error
    Rcpp::stop("Is this error unsafe?");
  });

}

可能不是——例如在 RcppParallel 文档中陈述的简单且经常重复的规则是 无论如何都不要联系 应该从多线程代码返回到 R,或者使用 R-created/owned内存。

从我的脑海里,我会

  • 脱离并行循环
  • 将错误条件或文本分配给字符串
  • 一次返回单线程代码调用Rcpp::stop(thattext)

Thomas Nagler 来自 RcppThread's GitHub 的回答:

您可以使用本机 C++ throw std::runtime_error(),它将被缓存,直到线程与主池同步回来。然后错误被推送到主线程,由 Rcpp 作为标准运行时错误处理并推送到 R.

所以:

#include <RcppThread.h>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppThread)]]

void myfun() {

  // parallel loop
  RcppThread::parallelFor(0, 100, [](int j){
    // do something that causes an error
    throw std::runtime_error("You did a bad thing");
  });

}