我使用 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/