安卓:与主线程本地线程的同步 [英] Android: Synchronization of native thread with main thread

查看:268
本文介绍了安卓:与主线程本地线程的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用程序,我已经得到了从本地线程到Java code这需要与主UI线程同步回调。的目的是,UI线程显示基于从本地线程返回的信息选项的列表。直到用户选择一个选项的本地线程需要阻塞。在用户选择一个选项,本地线程读取值,并继续运行。

In my android application I've got a callback from a native thread into Java code which needs to be synchronized with the main UI thread. The intention is that the UI thread display a list of options based on information returned from the native thread. Until the user selects an option the native thread needs to block. After the user selects an option the native thread reads the value and continues running.

我已经尝试使用ConditionVariable但是我得到一个VM错误的注释表明致命旋涂暂停,倾销线程来实现这个解决方案。

I've tried to implement this solution using a ConditionVariable however I get a VM error with the comment indicating "Fatal spin-on-suspend, dumping threads".

这看起来好像它不是可以使用一个基于Java的同步对象来同步这些线程。在code完全在那里我有两个Java线程的情况下。

It looks as if it's not possible to use a Java based synchronization object to synchronize these threads. The code works perfectly in the case where I've got two Java threads.

在总体上有什么办法可以使用​​基于Java的同步对象来同步Java和本地线程,或者这是否需要使用NDK通过调用从Java线程进入一个NDK的功能,实现了同步执行?

In general is there any way to use a Java based synchronization object to synchronize a Java and native thread, or does this need to be implemented using the NDK with a call from the Java thread into an NDK function that implements the synchronization?

推荐答案

要做到这一点的方法是不使用基于Java的同步对象,而是一个基于NDK同步对象,如下所示:

The way to do this is not to use a Java based sync object but rather an NDK based sync object as follows:

static pthread_cond_t  uiConditionVariable  = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t uiConditionMutex     = PTHREAD_MUTEX_INITIALIZER;



/**
 * This function opens the condition variable which releases waiting threads.
 */
JNIEXPORT void JNICALL
Java_com_Xxxx_openConditionVariable(JNIEnv *env,jobject o)
{
    pthread_mutex_lock(&uiConditionMutex);
    pthread_cond_signal(&uiConditionVariable);
    pthread_mutex_unlock(&uiConditionMutex);
}

/**
 * This function blocks on the condition variable associated with the 
 */
JNIEXPORT void JNICALL
Java_com_Xxxx_blockConditionVariable(JNIEnv *env,jobject o)
{
    pthread_mutex_lock(&uiConditionMutex);
    pthread_cond_wait(&uiConditionVariable,&uiConditionMutex);
    pthread_mutex_unlock(&uiConditionMutex);
}

这篇关于安卓:与主线程本地线程的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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