如何通过JNA从多个线程安全地调用C ++函数?

时间:2015-05-28 10:27:02

标签: java c++ multithreading java-native-interface jna

我使用JNA来调用用C ++编写的动态库中的函数。我注意到当从多个线程调用库中的C ++函数时会发生分段错误。

我的问题是如何通过JNA调用C ++函数并行而没有分段错误。在我的C ++代码中,没有引用任何外部数据,因此我认为可以并行执行C ++函数。

我确信多线程是分段错误的原因,因为使方法同步可以解决问题。换一种说法。换句话说,我知道添加synchronize或使用Native.synchronizedLibrary()通过以串行方式执行C函数来解决分段错误。但是,由于性能问题,我希望并行运行C ++函数。

public static interface MyCLibrary extends Library{
   ...
}

public static class RunnerClass implements Runnable{

  public void run(){
    callCfunc()
  }

  // Making this method synchronized suppress the error
  public void callCfunc(){
    MyCLibrary INSTANCE =  (MyCLibrary)Native.loadLibrary(MyCLibrary.JNA_LIBRARY_NAME, MyCLibrary.class);
    INSTANCE.cFunc()
  }
}

public static class MainClass {
  public static void main(){
      // When numThread = 1, the error does NOT occurr
      int numThread = 2;
      ExecutorService es = Executors.newFixedThreadPool(numThread);
      for (int i = 0; i < numThread; i++) {
          es.execute(new RunnerClass()));
      }
      es.shutdown();
      try {
          es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }

  }
}

1 个答案:

答案 0 :(得分:0)

我认为并行多次调用loadLibrary会导致段错误。 您应该加载一次并传递给RunnerClass的所有实例。