简体   繁体   中英

JNI Global Static Variables in C++ Code

I have a JNI C++ code being called from a multi-threaded java application

This C++ code has 2 global static variables a boolean and a string.

For some reason i keep getting segmentation fault from this code . Any idea what could lead to this ? I know this is not thread safe, but i am treating the variables as read only from the java application and only the C++ code is able to modify the values of these variables

Help much appreciated

EDIT : This code runs on a Linux machine . And runs for months at a time without any issues, then it issues a signal 11 segmentation fault and the JVM crashes.

If you're calling the C++ code from multiple threads, and the C++ code has global static variables, then it would be amazing if it worked. The simplest thing to try is to put a lock around the call, ie in the Java side change

native int callToCppFunction(int parameter);

to

synchronized native int callToCppFunction(int parameter);

to ensure that only one thread can be in the C++ code at a time.

Then there's another possible issue, which I bumped on about a year ago: apparently in Windows dlls it may not be enough to serialize calls to it (ie use synchronized ). They may also require to be called from the same thread each time . This answer offers an explanation to how that can be. The solution is to make a single threaded executor to the Java side, and route all calls to the native code through it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM