您如何在JNI环境的本机端正确同步线程? [英] How do you properly synchronize threads on the native side of a JNI environment?
问题描述
问题简介
我正在通过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 int
s 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.