小编emd*_*oll的帖子

Rcpp 矢量线程与 OpenMP 一起使用是否安全?

我使用 Rcpp 和 OpenMP 在 C++ 中进行并行计算。我读过在 Rcpp::List 线程中访问/设置元素安全吗?看来在线程代码块中使用 Rcpp 是危险的。但在 for 循环中读取或写入 Rcpp NumericVectors 是很常见的,例如https://gallery.rcpp.org/articles/hierarchical-risk-parity/

下面是我写的。任务很简单。我首先在(并行)for 循环之外声明NumericVector一个具有大尺寸的a 。n我做了一些计算并填充NumericVector使用索引的每个元素i。完成后,我计算出所需的分位数。

#include <Rcpp.h>
#include <omp.h>

// [[Rcpp::export]]
double foo(const int n, const int nthreads) {

  Rcpp::NumericVector out(n);
  #pragma omp parallel for num_threads(nthreads)
  for (int i = 0; i < n; ++i) {
    out[i] = doSomething();
  }

  Rcpp::Environment stats("package:stats");
  Rcpp::Function quantile = stats["quantile"];
  return Rcpp::as<double>(quantile(out, Rcpp::Named("probs") = 0.95));
}
Run Code Online (Sandbox Code Playgroud)

我有两个问题。

  1. 是否有任何理由使用其他容器(例如 …

c++ multithreading r rcpp

5
推荐指数
0
解决办法
334
查看次数

标签 统计

c++ ×1

multithreading ×1

r ×1

rcpp ×1