我对
mcmapply
有问题,只有在 Rcpp 函数 testfun()
首先在 mcmapply
外部调用,然后通过 mcmapply
调用时才会出现。该问题仅在以下情况下存在:
testfun()
使用 openMP
mcmapply
使用并行化 (mc.cores
>1)如果我用
mcmapply
调用 testfun()
,它会运行并完成,不会出现错误。如果我先单独调用 testfun()
,然后再调用 mcmapply
,那么 mcmapply
就会停止。
MWE:
Rcpp::sourceCpp(code=
" #include <RcppArmadillo.h>;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
void testfun(int n) {
arma::mat foo = arma::sqrt(arma::zeros(n,n));
}")
library(parallel)
print("Run mcmapply+testfun: works")
mcmapply(mc.cores=2, function(x) testfun(100), 1:2)
print("Calling testfun separately: works")
testfun(100)
print("Run mcmapply+testfun after having run testfun separately: stalls")
mcmapply(mc.cores=2, function(x) testfun(100), 1:2)
这与 openMP 的使用有关,我怀疑问题与存储矩阵有关,因为只有当
testfun()
将 arma::sqrt()
的结果分配给 arma::mat
时才会发生。如果我指定 #define ARMA_DONT_USE_OPENMP
,则不会出现该问题。
设置:使用 R 4.4.0、gcc 14.2.0 和 gsl 2.7.1 的 linux,但问题也出现在旧版 R 版本上。
这违反了有据可查的规则(例如,参见几天前的这篇文章),即您不能从并行部分回调到 R,或触摸 R 对象。 为了方便和默认,RcppArmadillo 向量和矩阵使用 R 内存,这违反了它。 请参阅 RcppParallel 小插图进行讨论,并查看其 RVector 和 RMatrix 类的示例。