gpt4 book ai didi

java - 如何在 JNI 环境的 native 端正确同步线程?

转载 作者:可可西里 更新时间:2023-11-01 16:18:45 25 4
gpt4 key购买 nike

问题简介

我通过 JNI 在一个进程中使用 C++ 和 Java。对于有问题的用例,C++ 线程和 Java 线程都在访问相同的数据,它们是在 C++ 端这样做的,我想正确同步访问。

到目前为止,我几乎所有的 JNI 线程同步都在 Java 端,答案很明显:使用提供的 Java 并发包和内置的并发语言功能。不幸的是,答案在 C++ 方面并不是那么明显。

到目前为止我尝试过的内容简介

我尝试使用 pthreads 互斥锁,认为即使我没有使用 pthreads 来创建线程它也可以工作,但是在尝试锁定时偶尔会卡住 - 我将在下面进一步展示一个示例。

问题详情

在我目前的特定用法中,c++ 正在轮询 Java 提供的更改,以 1 秒计时器(不是我想要的,但我不确定如何使其成为事件驱动的,因为遗留 c++ 代码的性质) )。 Java 线程通过调用 native 函数提供数据,c++ 将数据复制到 c++ 结构中。

这是代码中的情况类型(发生在 2 个线程上,Thread1 和 Thread2):

代码示例

请注意一个 SSCCE,因为它缺少 TheData 的定义和 TheDataWrapper ,但它们包含什么并不重要。假设它们只包含几个公共(public) int如果这有助于您的思考过程(不过,在我的情况下,它实际上是多个 int 数组和 float 数组)。

C++:

class objectA
{
void poll();
void supplyData(JNIEnv* jni, jobject jthis, jobject data);
TheDataWrapper cpp_data;
bool isUpdated;

void doStuff(TheDataWrapper* data);
};

// poll() happens on a c++ thread we will call Thread1
void objectA :: poll()
{
// Here, both isUpdated and cpp_data need synchronization

if(isUpdated)
{
do_stuff(&cpp_data);
isUpdated = false;
}
}

// supplyData happens on the Thread2, called as a native function from a java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
// some operation happens that copies the java data into a c++ equivalent
// in my specific case this happens to be copying ints/floats from java arrays to c++ arrays
// this needs to be synchronized
cpp_data.copyFrom(data);
isUpdated = true;
}

java :
class ObjectB
{
// f() happens on a Java thread which we will call Thread2
public void f()
{
// for the general case it doesn't really matter what the data is
TheData data = TheData.prepareData();
supplyData(data);
}

public native void supplyData(TheData data);
}

到目前为止我尝试过的细节

当我尝试如下 pthread 锁定时,有时执行会卡在 pthread_mutex_lock .在这种情况下不应该出现死锁,但为了进一步测试,我运行了一个场景,其中 supplyData根本没有被调用(没有提供数据),所以应该不会出现死锁,但第一次调用 poll反正偶尔会挂。也许在这种情况下使用 pthreads 互斥锁不是一个好主意?或者也许我做了一些愚蠢的事情并一直忽视它。

到目前为止,我尝试使用 pthreads 如下:

代码示例

C++:
class objectA
{
pthread_mutex_t dataMutex;
... // everything else mentioned before
}

// called on c++ thread
void objectA :: poll()
{
pthread_mutex_lock(&dataMutex);

... // all the poll stuff from before

pthread_mutex_unlock(&dataMutex);
}

// called on java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
pthread_mutex_lock(&dataMutex);

... // all the supplyData stuff from before

pthread_mutex_unlock(&dataMutex);
}

我想过但没有做的另一种选择

我也考虑过使用JNI回调java,使用java的并发控制来请求锁。这应该可以工作,因为任何一个线程都应该根据需要在 java 端阻塞。然而,由于从 C++ 访问 java 过于冗长,我希望避免经历这种头痛。我可能可以制作一个 C++ 类,它将 JNI 调用封装到 java 中以请求 java 锁;这将简化 C++ 代码,尽管我想知道为了线程锁而在 JNI 上来回交叉的开销。

根据@Radiodef 的评论,这似乎没有必要。看来 JNI 包括 MonitorEnter/ MonitorExit已经在 C++ 端处理锁定的函数。在 Java 端同时使用这些和常规锁时存在缺陷,所以 please read here使用前。我会尝试这个,我希望 MonitorEnter/ MonitorExit将是答案,我建议@Radiodef 根据评论做出回答。

关闭

我怎么能正确同步呢? pthread_mutex_(un)lock 应该工作吗?如果没有,我可以用什么来在 C++ 线程和 Java 线程之间进行同步?

这里没有提供特定于 JNI 的 C++ 代码,因为 JNI 桥正在工作,我可以来回传递数据。这个问题特别是关于 c++/java 线程之间的正确同步,否则这些线程可以正确通信。

如前所述,我宁愿避免轮询方案,但这可能最终成为另一个问题。遗留的 c++ 代码在 X/motif 中显示其用户界面的一部分,如果我没记错的话,上面的 c++ 线程恰好是用于显示的事件线程。一旦插入此类的 Java 用户界面,java 线程将最终成为 java 事件调度线程,尽管现在 java 线程是一个自动化测试线程;无论哪种方式,它都是一个单独的 Java 线程。

C++ 线程附加到 JVM。事实上,那是创建JVM的C++线程,所以默认应该是附加的。

我已经成功地将其他 Java 用户界面元素插入到这个程序中,但这是 C++ 第一次需要来自 Java 的需要同步的非原子数据。有没有普遍接受的正确方法来做到这一点?

最佳答案

如果两个线程都附加到 JVM,那么您可以通过 JNIEnv 访问 JNI 的同步。的 MonitorEnter(jobject)MonitorExit(jobject)职能。就像听起来一样,MonitorEnter获得对提供的 jobject 的锁定, 和 MonitorExit释放对提供的 jobject 的锁.

注意:有一些陷阱需要注意!注意 MonitorEnter 的倒数第二段的描述和MonitorExit的最后一段关于混搭的说明MonitorEnter/MonitorExit与您可能认为兼容的其他类似机制。

here

MonitorEnter

jint MonitorEnter(JNIEnv *env, jobject obj);

Enters the monitor associated with the underlying Java object referred to by obj. Enters the monitor associated with the object referred to by obj. The obj reference must not be NULL. Each Java object has a monitor associated with it. If the current thread already owns the monitor associated with obj, it increments a counter in the monitor indicating the number of times this thread has entered the monitor. If the monitor associated with obj is not owned by any thread, the current thread becomes the owner of the monitor, setting the entry count of this monitor to 1. If another thread already owns the monitor associated with obj, the current thread waits until the monitor is released, then tries again to gain ownership.

A monitor entered through a MonitorEnter JNI function call cannot be exited using the monitorexit Java virtual machine instruction or a synchronized method return. A MonitorEnter JNI function call and a monitorenter Java virtual machine instruction may race to enter the monitor associated with the same object.

To avoid deadlocks, a monitor entered through a MonitorEnter JNI function call must be exited using the MonitorExit JNI call, unless the DetachCurrentThread call is used to implicitly release JNI monitors.

LINKAGE:

Index 217 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.





MonitorExit

jint MonitorExit(JNIEnv *env, jobject obj);

The current thread must be the owner of the monitor associated with the underlying Java object referred to by obj. The thread decrements the counter indicating the number of times it has entered this monitor. If the value of the counter becomes zero, the current thread releases the monitor.

Native code must not use MonitorExit to exit a monitor entered through a synchronized method or a monitorenter Java virtual machine instruction.

LINKAGE:

Index 218 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

EXCEPTIONS:

IllegalMonitorStateException: if the current thread does not own the monitor.



因此,问题中尝试使用 pthreads 的 C++ 代码应更改如下(代码假定 JNIEnv* 指针是以典型的 JNI 方式事先以某种方式获取的):
class objectA
{
jobject dataMutex;
... // everything else mentioned before
}

// called on c++ thread
void objectA :: poll()
{
// You will need to aquire jniEnv pointer somehow just as usual for JNI
jniEnv->MonitorEnter(dataMutex);

... // all the poll stuff from before

jniEnv->MonitorExit(dataMutex);
}

// called on java thread
void objectA :: supplyData(JNIEnv* jni, jobject jthis, jobject data)
{
// You will need to aquire jniEnv pointer somehow just as usual for JNI
jniEnv->MonitorEnter(dataMutex);

... // all the supplyData stuff from before

jniEnv->MonitorExit(dataMutex);
}

感谢提供答案的@Radiodef。不幸的是,这是作为评论。我一直等到第二天下午,让 Radiodef 有时间做出答复,所以现在我正在这样做。感谢 Radiodef 提供我解决此问题所需的插入。

关于java - 如何在 JNI 环境的 native 端正确同步线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com