JNI线程模型? [英] JNI thread model?

查看:84
本文介绍了JNI线程模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从Java调用C/C ++时,是JavaVM或JNI创建的新线程来在我的Java线程等待时运行C/C ++代码吗? 我之所以这样问,是因为我的C/C ++代码在GPU上运行了某些程序,因此我需要检查特定的缓冲区以返回结果.得到结果后,需要再次调用Java函数.

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.

因此,我想在C ++端创建一个线程,以不断检查缓冲区,一旦有可用数据,就调用Java端.

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.

推荐答案

JNI在后台不创建任何新线程.本机函数在与调用本机函数的java方法相同的线程中执行.反之亦然,当本机代码调用java方法时,该java方法与调用该方法的本机代码在同一线程中执行.

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.

这有其后果-当本机函数返回时,本机函数调用将返回到Java代码,而当被调用的java方法返回时,本机代码将继续执行.

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.

当本机代码执行应在单独的线程中运行的处理时,必须显式创建该线程.您可以创建一个新的Java线程并从此专用线程中调用本机方法.或者,您可以在本机代码中创建一个新的本机线程,将其启动并从本机函数返回.

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);    
}

如果使用第二个变体,并且要从本机创建的线程中调用Java回调,则必须将该线程附加到JVM.怎么做?请参阅 JNI附加/分离线程内存管理 ...

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 ...

这篇关于JNI线程模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆