Java 如何安全地调用C++;通过JNA从多个线程执行函数? < >我使用JNA调用C++中动态库中的函数。我注意到,当从多个线程调用库中的C++函数时,出现了一个分割错误。 我的问题是如何在没有分割错误的情况下,通过JNA调用C++函数 >并行。在我的C++代码中,没有引用外部数据,所以我相信并行执行C++函数是可能的。
我确信多线程是分段错误的原因,因为同步方法可以抑制问题。换句话说。换句话说,我知道添加Java 如何安全地调用C++;通过JNA从多个线程执行函数? < >我使用JNA调用C++中动态库中的函数。我注意到,当从多个线程调用库中的C++函数时,出现了一个分割错误。 我的问题是如何在没有分割错误的情况下,通过JNA调用C++函数 >并行。在我的C++代码中,没有引用外部数据,所以我相信并行执行C++函数是可能的。,java,c++,multithreading,java-native-interface,jna,Java,C++,Multithreading,Java Native Interface,Jna,我确信多线程是分段错误的原因,因为同步方法可以抑制问题。换句话说。换句话说,我知道添加synchronize或使用Native.synchronizedLibrary()可以通过串行方式执行C函数来解决分段错误。但是,由于性能问题,我希望并行运行C++函数。 public static interface MyCLibrary extends Library{ ... } public static class RunnerClass implements Runnable{ pu
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();
}
}
}
公共静态接口MyCLibrary扩展库{
...
}
公共静态类RunnerClass实现Runnable{
公开募捐{
callCfunc()
}
//使此方法同步将抑制错误
public void callCfunc(){
MyCLibrary实例=(MyCLibrary)Native.loadLibrary(MyCLibrary.JNA_LIBRARY_NAME,MyCLibrary.class);
INSTANCE.cFunc()
}
}
公共静态类main类{
公共静态void main(){
//当numThread=1时,不会发生错误
int numThread=2;
ExecutorService es=Executors.newFixedThreadPool(numThread);
for(int i=0;i
我认为并行多次调用loadLibrary是导致SEG故障的原因。
您应该加载它一次并将其传递给RunnerClass的所有实例。不幸的是,它不能解决问题。我很抱歉忘记提到这一点,但是我已经试过了。C++的代码。也许它不是可重入的?@AndrewHenle谢谢你,也许你的猜测是真的。经过另一项研究和您的评论,现在我相信可重入发生了这个问题。在发布这个问题之前,我认为动态库的内存空间是为每个线程新创建的,而不是在多个线程中共享的。但是,我的想法似乎是错误的。我需要创建线程安全的C++代码,显然我的C++代码不是线程安全的。但是,很难更新我的C++代码以线程安全。所以,我认为我的问题应该是“如何为Java中多线程调用的动态库创建不同的内存空间,以避免重入”。我应该更新原始问题还是关闭这个问题,并创建新的问题?因为它是不可重入的C++代码,IMO最好在那里修复它。创建一个静态互斥锁,在进入方法时锁定它,并在方法返回之前将其解锁。@ AndrewHenle谢谢,但是,我希望并行执行C++函数,因为性能问题。