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

标签 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();
      }

  }
}

最佳答案

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

关于java - 如何通过 JNA 从多个线程安全地调用 C++ 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30503887/

相关文章:

multithreading - 如何从JavaFX中的单独线程更新状态和进度

c# - .Net ThreadPool 线程是如何创建的?

java - 循环javaBean属性

java - Minecraft 插件前缀 (Java)

java - 调用不同类中的方法并传递数组

c++ - 通过 map.equal_range 问题 interator

java - 使用另一个 jPanel 上的按钮修改 jPanel

c++ - 找出特定整数有多少个二进制数字

c++ - 条件变量的谓词

c++ - 删除 vector 中指针的适当方法