Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenMP doesn't run parallel with JNI

I have a c++ code that uses openMP to run in parallel.

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.

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.

Do you know how to fix this?

like image 730
Bob Avatar asked Mar 25 '26 05:03

Bob


1 Answers

Indeed, your current problem was answered by @Andrew Henle in the comments: you need to use -fopenmp during both the compilation and linking steps.

However, I wanted to expand and say that your code as-is presents a textbook case of when to use 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; and (b) Easily allowing for an extension for more sections and/or more threads. OpenMP handles all load balancing for you if you have more sections than threads.

like image 150
NoseKnowsAll Avatar answered Mar 26 '26 19:03

NoseKnowsAll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!