获取线程号的 Pragma 指令不起作用 Rcpp

Pragma directive to get thread number not working Rcpp

我正在尝试使用 Rcpp 中的 pragma 指令并行化循环。除了在编译过程中出现无法识别 pragma 的警告消息(尽管从我所读的内容来看这似乎不是问题),其他 pragma 命令不起作用。这是我一直在使用的最小示例(for 循环的内容无关紧要):

sourceCpp(code = '
#include <Rcpp.h>
#include <omp.h>
using namespace Rcpp ; 

// [[Rcpp::export]]
int test() {

#pragma omp parallel for
int foo = omp_get_num_threads() ;
for(int i = 0; i < 2; i++) {
  Rcout << i ;
}
return foo ;

}')

这是我的错误:

"C:/rtools40/mingw64/bin/"g++ -std=gnu++11  -I"C:/PROGRA~1/R/R-40~1.4/include" -DNDEBUG   -I"C:/Users/User/Documents/R/win-library/4.0/Rcpp/include" -I"C:/Users/User/AppData/Local/Temp/RtmpWW0LXx/sourceCpp-x86_64-w64-mingw32-1.0.4.6"        -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign -c file2fe83fae2189.cpp -o file2fe83fae2189.o
file2fe83fae2189.cpp:9: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]
 #pragma omp parallel for
 
C:/rtools40/mingw64/bin/g++ -std=gnu++11 -shared -s -static-libgcc -o sourceCpp_90.dll tmp.def file2fe83fae2189.o -LC:/PROGRA~1/R/R-40~1.4/bin/x64 -lR
C:/rtools40/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: file2fe83fae2189.o:file2fe83fae2189.cpp:(.text+0x106): undefined reference to `omp_get_num_threads'
collect2.exe: error: ld returned 1 exit status

我在 Windows 机器上,因此 MacOS 编译器问题不应该适用,我的 num_threads 调用在 pragma 部分内。关于这里出了什么问题有什么想法吗?

虽然这些东西可能很挑剔,但您 显然错过了一个事实 您必须通知 Rcpp 您想要 OpenMP 编译:您通过插件(或在包中)执行此操作,这是您应该通过 src/Makevarssrc/Makevars.win 变量使用的方式。

无论如何,这是一个我刚刚从我闲逛的旧 C++ 示例中派生出来的工作示例。

代码

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

// [[Rcpp::plugins(openmp)]]

// [[Rcpp::export]]
int foo() {
    
    int th_id, nthreads;

#pragma omp parallel private(th_id)
    {
        th_id = omp_get_thread_num();
        std::ostringstream ss;  // allow for better synchronization
        ss << "Hello World from thread " << th_id << std::endl;
        Rcpp::Rcout << ss.str();
#pragma omp barrier
#pragma omp master
        {
            nthreads = omp_get_num_threads();
            Rcpp::Rcout << "There are " << nthreads << " threads" << std::endl;
        }
    }
    return 0;
}

/*** R
foo()
*/

输出

在我的超线程六核机器上cpu:

> Rcpp::sourceCpp("answer.cpp")

> foo()
Hello World from thread 0
Hello World from thread 1
Hello World from thread 8
Hello World from thread 10
Hello World from thread 4
Hello World from thread 9
Hello World from thread 11
Hello World from thread 7
Hello World from thread 3
Hello World from thread 5
Hello World from thread 6
Hello World from thread 2
There are 12 threads
[1] 0
>