您如何在JNI环境的本机端正确同步线程? [英] How do you properly synchronize threads on the native side of a JNI environment?

查看:51
本文介绍了您如何在JNI环境的本机端正确同步线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题简介

我正在通过JNI在一个过程中使用C ++和Java.对于有问题的用例,C ++线程和Java线程都在访问相同的数据,它们都在C ++端进行访问,因此我想正确地同步访问.

I am using C++ and Java in one process via JNI. For the use case in question, both a C++ thread and a Java thread are accessing the same data, they are doing so on the C++ side, and I want to properly synchronize the access.

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

So far, almost all of my JNI thread synchronization has been on the Java side where the answer is obvious: use the provided Java concurrency package and the built-in concurrency language features. Unfortunately, the answer is not so obvious on the C++ side.

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

我尝试使用pthreads互斥锁,即使我不使用pthreads创建线程也认为它可能会起作用,但是在尝试锁定时偶尔会卡住-我将在下面进一步说明该示例.

I tried using a pthreads mutex thinking that it might work even though I'm not using pthreads to create threads, but that occasionally gets stuck when trying to lock - I'll show an example of that farther below.

在我当前的特定用法中,c ++会在1秒钟的计时器上轮询Java提供的更改(这不是我想要的,但是鉴于不确定的性质,我不确定如何将其变为事件驱动的)旧版C ++代码).Java线程通过调用本机函数来提供数据,然后c ++将数据复制到c ++结构中.

In my current, specific usage, c++ is polling for changes provided by Java on a 1 second timer (not what I'd like, but I'm not sure how I would make it event-driven given the nature of the legacy c++ code). The Java thread provides data by calling a native function and c++ copies the data into a c++ structure.

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

This is the type of situation in code (happens on 2 threads, Thread1 and Thread2):

代码示例

请注意一个SSCCE,因为它缺少 TheData TheDataWrapper 的定义,但是它们所包含的内容并不重要.假设它们只包含几个公共的 int ,如果这有助于您的思考过程(尽管在我看来,它实际上是int的多个数组和float的数组).

Note quite an SSCCE, as it's missing definitions for TheData and TheDataWrapper, but it doesn't really matter what they contain. Assume they merely contain a couple of public ints if that helps your thought process (though, in my case, it's actually multiple arrays of int and arrays of 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互斥锁可能不是一个好主意吗?或者,也许我做了一些愚蠢的事情,然后继续忽略它.

What I've Tried so far Details

When I tried pthread's locking as below, sometimes execution gets stuck in pthread_mutex_lock. There should not be a deadlock in this situation, but just to test further I ran a scenario where supplyData was not getting called at all (no data was being supplied), so no deadlock should have been possible, yet the first call to poll will occasionally hang anyway. Perhaps using a pthreads mutex is not a good idea in this situation? Or perhaps I did something stupid and keep overlooking it.

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

So far, I tried using pthreads as below:

代码示例

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过于冗长,因此我希望避免遇到这种麻烦.我可能可以制作一个将JNI调用封装到Java中以请求Java锁的c ++类;这将简化c ++代码,尽管我想知道仅针对线程锁在JNI上来回交叉的开销.

I also considered using JNI to call back into java to request a lock using java's concurrency control. That should work, as either thread should block on the java side as needed. However, since accessing java from c++ is overly verbose, I was hoping to avoid going through that headache. I probably could make a c++ class which encapsulates JNI calls into java to request a java lock; that would simplify c++ code, though I wonder about the overhead of crossing back and forth over JNI just for thread locks.

根据@Radiodef的评论,似乎这不是必需的.看来JNI包括 MonitorEnter / MonitorExit 函数,这些函数已经处理了c ++方面的锁定.与Java端的常规锁同时使用时,存在一些陷阱,因此

It seems this is not necessary, per the comment by @Radiodef. It appears JNI includes MonitorEnter/MonitorExit functions which already handle the locking on the c++ side. There are pitfalls when using these at the same time as conventional locks on the java side, so please read here before using. I will be trying this out, and I expect that MonitorEnter/MonitorExit will be the answer and I recommend @Radiodef make an answer out of the comment.

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

How could I properly synchronize this? Should pthread_mutex_(un)lock work? If not, what can I use to synchronize between the C++ thread and the Java thread?

由于JNI桥正在工作,并且我可以来回传递数据,所以这里没有提供特定于JNI的C ++代码.问题特别是关于正确进行通信的c ++/java线程之间的正确同步.

No JNI-specific C++ code is provided here since the JNI bridge is working and I can pass data back and forth. The question is specifically about proper synchronization between c++/java threads that are otherwise correctly communicating.

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

As mentioned before, I would prefer to avoid the polling scheme, but that might end up being another question. The legacy c++ code displays its part of the user interface in X/motif, and if I recall correctly the c++ thread above happens to be the event thread for display. The java thread will end up being the java event dispatch thread once the java user interface for this class is plugged in, though for now the java thread is an automated test thread; either way, it's a separate java thread.

C ++线程已附加到JVM.实际上,这就是创建JVM的C ++线程,因此默认情况下应该附加它.

The C++ thread is attached to the JVM. In fact, that is the C++ thread that created the JVM, so it should be attached by default.

我已经成功地将其他Java用户界面元素插入此程序,但这是C ++第一次需要Java的非原子数据需要进行同步.有普遍公认的正确方法吗?

I have been successful with plugging in other Java user interface elements into this program, but this is the first time C++ has needed non-atomic data from Java which needed to be synchronized. Is there a generally accepted correct way to do this?

推荐答案

如果两个线程都已附加到JVM,则可以通过 JNIEnv MonitorEnter(jobject) MonitorExit(jobject)函数.听起来, MonitorEnter 在提供的 jobject 上获得了锁定,而 MonitorExit 释放了在提供的 jobject 上的锁定.>.

If both threads are attached to the JVM, then you can access the JNI's synchronization via JNIEnv's MonitorEnter(jobject) and MonitorExit(jobject) functions. Just as it sounds, MonitorEnter aquires a lock on the provided jobject, and MonitorExit releases the lock on the provided jobject.

注意:有一些陷阱需要注意!请注意 MonitorEnter 的描述的倒数第二段和 MonitorExit 的描述的最后一段,有关混合和匹配 MonitorEnter /MonitorExit 与您可能认为兼容的其他类似机制.

NOTE: There are some pitfalls to be aware of! Notice the second to last paragraph of MonitorEnter's description and the last paragraph of MonitorExit's description about mixing and matching MonitorEnter/MonitorExit with other similar mechanisms which you might otherwise think are compatible.

请参见

MonitorEnter

jint MonitorEnter(JNIEnv * env,jobject obj);

jint MonitorEnter(JNIEnv *env, jobject obj);

输入与引用的基础Java对象关联的监视器到obj.输入与所引用对象关联的监视器由obj.obj引用不能为NULL.每个Java对象都有一个与之关联的监视器.如果当前线程已经拥有与obj关联的监视器,它将在监视器中增加一个计数器指示此线程已进入监视器的次数.如果与obj关联的监视器不归任何线程所有,因此当前线程成为监视器的所有者,设置条目此监视器的计数为1.如果另一个线程已经拥有该监视器与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.

通过MonitorEnter JNI函数调用输入的监视器不能使用monitorexit Java虚拟机指令或同步方法返回.MonitorEnter JNI函数调用和monitorenter Java虚拟机指令可能会争先进入与同一对象关联的监视器.

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.

为避免死锁,通过MonitorEnter JNI输入的监视器除非使用MonitorExit JNI调用,否则必须退出函数调用,除非DetachCurrentThread调用用于隐式释放JNI显示器.

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.

链接:

JNIEnv接口功能表中的索引217.

Index 217 in the JNIEnv interface function table.

参数:

env:JNI接口指针.

env: the JNI interface pointer.

obj:普通的Java对象或类对象.

obj: a normal Java object or class object.

退货:

成功返回"0";失败时返回负值.

Returns "0" on success; returns a negative value on failure.

MonitorExit

jint MonitorExit(JNIEnv * env,jobject obj);

jint MonitorExit(JNIEnv *env, jobject obj);

当前线程必须是与之关联的监视器的所有者obj引用的基础Java对象.线程递减计数器,指示它已输入此次数监视器.如果计数器的值变为零,则当前线程释放监视器.

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.

本机代码不得使用MonitorExit退出通过以下方式输入的监视器同步方法或监视者Java虚拟机指示.

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

链接:

JNIEnv接口功能表中的索引218.

Index 218 in the JNIEnv interface function table.

参数:

env:JNI接口指针.

env: the JNI interface pointer.

obj:普通的Java对象或类对象.

obj: a normal Java object or class object.

退货:

成功返回"0";失败时返回负值.

Returns "0" on success; returns a negative value on failure.

例外:

IllegalMonitorStateException:如果当前线程不拥有监视器.

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

因此,尝试使用pthreads的问题中的C ++代码应作如下更改(代码假定 JNIEnv * 指针是以典型的JNI方式预先获得的):

So the C++ code in the question which attempted to use pthreads should be changed as following (code assumes the JNIEnv* pointer was acquired somehow beforehand in typical JNI fashion):

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提供我需要解决的问题.

Kudos to @Radiodef who provided the answer. Unfortunately it was as a comment. I waited until afternoon next day to allow time for Radiodef to make it an answer, so now I'm doing it. Thank you Radiodef for providing the nudge I needed to fix this.

这篇关于您如何在JNI环境的本机端正确同步线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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