JNI thread model?

我只是一个虾纸丫 提交于 2021-02-17 21:47:10

问题


When I call a C/C++ from Java, is a new thread created by JavaVM or JNI to run the C/C++ code while my Java thread is waiting? I ask this because my C/C++ code runs something on the GPU and I need to check a specific buffer to get the result back. Once I have the result, I need to call my Java function again.

So I was thinking of creating a thread on the C++ side that continuously checks the buffer and once there is some data available, makes a call back to the Java side.


回答1:


The JNI does not create any new thread behind the scene. A native function is executed in the same thread as the java method that calls the native function. And vice versa when native code calls a java method then the the java method is executed in the same thread as the native code calling the method.

It has consequence - a native function call returns to java code when the native function returns and native code continues execution when a called java method returns.

When a native code does a processing that should run in a separate thread the the thread must be explicitly created. You can either create a new java thread and call a native method from this dedicated thread. Or you can create a new native thread in the native code, start it and return from the native function.

// Call a native function in a dedicated java thread
native void cFunction();
...
new Thread() {
    public void run() {
        cFunction();
    }
};

// Create a native thread - java part
native void cFunction()
...
cFunction();

//  Create a native thread - C part
void *processing_function(void *p);
JNIEXPORT void JNICALL Java____cFunction(JNIEnv *e, jobject obj) {
    pthread_t t;
    pthread_create(&t, NULL, processing_function, NULL);    
}

If you use the second variant and you want to call a java callback from a thread created natively you have to attach the thread to JVM. How to do it? See the JNI Attach/Detach thread memory management ...



来源:https://stackoverflow.com/questions/38378901/jni-thread-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!