- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
问题简介
我通过 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;
}
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_mutex_lock
.在这种情况下不应该出现死锁,但为了进一步测试,我运行了一个场景,其中
supplyData
根本没有被调用(没有提供数据),所以应该不会出现死锁,但第一次调用
poll
反正偶尔会挂。也许在这种情况下使用 pthreads 互斥锁不是一个好主意?或者也许我做了一些愚蠢的事情并一直忽视它。
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);
}
MonitorEnter
/
MonitorExit
已经在 C++ 端处理锁定的函数。在 Java 端同时使用这些和常规锁时存在缺陷,所以
please read here使用前。我会尝试这个,我希望
MonitorEnter
/
MonitorExit
将是答案,我建议@Radiodef 根据评论做出回答。
最佳答案
如果两个线程都附加到 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.
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);
}
关于java - 如何在 JNI 环境的 native 端正确同步线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420937/
我有一个使用 css 列的下拉菜单,当我使用 jquery slide() 时,它会调整下拉框的大小,并重排内容直到达到完整高度。 这是一个工作示例 https://codepen.io/peterg
我有一个带有嵌套 ScrollViewer 的 Expander,如下所示: 代码(简化版)
我想在所有 ajax 调用之后调用一些 javascript 函数。我知道如何调用每个单独的 ajax 调用中的函数,如下所示: function xyz() { if (window.XMLHttp
我想将值从应用程序端传递到 api。在此 api 调用中传递图像、名字、电子邮件、电话和位置。在 Debug模式下,检查值不会被传递。 代码下方 File file = null;
我正在尝试在使用reportlab生成的pdf中的表格后插入分页符,我正在使用以下函数生成pdf: def render_to_pdf(template_src, context_dict): t
CBPeripheralManager 是否有推荐的方法来终止连接。到目前为止我发现的最好的方法就是干脆不响应动态值,然后 BLE 堆栈似乎关闭了连接,但这似乎很粗糙。 一定有更好的方法吗? 最佳答案
我的 API 的 REST 端位于以下地址:http://test.jll.aplikacje-dedykowane.pl/rest/warehouse/all 。现在,我尝试返回在此页面准备的 JS
我有以下 CPP 代码。我想做的是,当我的 native 端发生错误时,我会通知 Java 该错误。我用了How can I catch SIGSEGV (segmentation fault) an
限制对象的方法之一是像这样给函数添加限制 def ten_objects(): obj = Model.objects.all()[0:10] # limit to 10 retur
我目前在电信公司实习,这是一个专业,也是本科生。我有很多选择。据我所知,我知道独立应用程序端的 c、c++、c#、java 语言,在移动端我尝试进入 android 世界,也知道 php、mysql、
我想让我的边框底部看起来像这样: 有一个 flex 的末端。目前它看起来像这样: 我尝试使用的 CSS 是 border-bottom-right-radius: 10px;。代码如下所示:
我有一个 Flutter 项目,突然间,据我所知,我没有做任何特别的事情..Android 端开始显示错误,我完全迷路了,我完全不知道哪里出了问题,也不知道为什么会这样。 这就是我打开 android
我有一个自定义对象列表 (List) 。我需要将此数据发送到 React Native 端以显示在平面列表中。我该怎么做?这个列表出现在 类 NativeToReact(reactContext:Re
我有这个代码: #if defined(NOT_STANDALONE) JNIEXPORT void JNICALL sumTraces (JNIEnv* env, jclass caller,
我有一个定义一对多模型关系的 Django 应用程序。模型如下所示: from django.db import models # Create your models here. class Str
我有以下代码,它根据 IFrame 内容的大小调整 IFrame 的大小: function setIframeHeight(id) {
如何创建自定义过滤器 angularjs javascript Controller 端?我想通过 SegmentId 在名为段的数组中搜索,以创建过滤器,该过滤器通过 SegmentId 在段数组搜
我的代码在 netbeans 8.0.2 中我几乎尝试了所有方法,但没有结果。请帮助我。如何在 netbeans 中显示它? 最佳答案 您只需单击源包(源文件),它就会显示您的项目文件。 关于java
我想这是纯 C++ 问题和 OpenGL 问题之间的一种交叉。我有一个统一的缓冲区,并在其中分配 sizeof(ShaderData) 字节的空间。我在着色器的 GPU 端使用 std140 布局。
我对 Hadoop 中 reduce 端的文件合并过程的理解有问题,因为它在“Hadoop:权威指南”(Tom White)中有所描述。引用它: When all the map outputs ha
我是一名优秀的程序员,十分优秀!