简体   繁体   English

OpenMP不与JNI并行运行

[英]OpenMP doesn't run parallel with JNI

I have a c++ code that uses openMP to run in parallel. 我有一个使用openMP并行运行的c ++代码。

void f(){
omp_set_num_threads(3);
#pragma omp parallel 
{
if (omp_get_thread_num() == 0 ){

      // do task 1   

}else if (omp_get_thread_num() == 1){

     //do task 2

}else if (omp_get_thread_num() == 2){

     //do task 3
}}

I use SWIG JNI to create a dll and call this code from Java. 我使用SWIG JNI创建一个DLL并从Java调用此代码。

System.loadLibrary("model");
model.f();

It runs in serial mode. 它以串行模式运行。 When I compile the code directly with c++ and run in command line, it runs parallel. 当我使用c ++直接编译代码并在命令行中运行时,它会并行运行。

Do you know how to fix this? 你知道怎么解决这个问题吗?

Indeed, your current problem was answered by @Andrew Henle in the comments: you need to use -fopenmp during both the compilation and linking steps. 实际上,@Andrew Henle在评论中回答了您当前的问题:您需要在编译和链接步骤中使用-fopenmp

However, I wanted to expand and say that your code as-is presents a textbook case of when to use OpenMP sections . 但是,我想扩展并说明你的代码是一个教科书案例,说明何时使用OpenMP sections You should change your code to take advantage of these semantics: 您应该更改代码以利用这些语义:

void f() {
    omp_set_num_threads(3);
    #pragma omp parallel sections
    {
        #pragma omp section
        {
            // do task 1   
        }
        #pragma omp section
        {
            //do task 2
        }
        #pragma omp section
        {
            //do task 3
        }
    }
}

This has the advantage of (a) becoming serial code when you do not compile with OpenMP support, one of the original tenets of OpenMP; 这具有以下优点:(a)当您不使用OpenMP支持进行编译时成为串行代码,这是OpenMP的原始原则之一; and (b) Easily allowing for an extension for more section s and/or more threads. (b)轻松允许更多section和/或更多线程的扩展。 OpenMP handles all load balancing for you if you have more section s than threads. 如果您有比线程更多的section OpenMP会为您处理所有负载平衡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM