gpt4 book ai didi

android - 如何从 JNI 启动一个新线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:40:25 24 4
gpt4 key购买 nike

我需要从 android 应用程序的 native 部分启动一个新线程。它必须在 JNI 中声明和定义。有人知道我该怎么做吗?如果有人会发布示例,我将非常高兴。

最佳答案

最简单的方法是使用 C++11 线程类。参见 this topic关于如何使用 Android NDK 启用 C++11。另见 this post如果您在让线程类工作时遇到问题。然后你可以像这样使用它:

#include <thread>         // std::thread

void foo()
{
// do stuff...
}

void bar(int x)
{
// do stuff...
}

JNIEXPORT void JNICALL
Java_org_testjni_android_Game_someFunction(JNIEnv * env, jobject obj)
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)

//main, foo and bar now execute concurrently

// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes

}

如果你不能使用 C++11,只需使用 pthread(POSIX 线程),这没什么不同,除了它像旧的 C:

#include <pthread.h>

//This function will be called from a thread

void *call_from_thread(void *) {
//do stuff
return NULL;
}

JNIEXPORT void JNICALL
Java_org_testjni_android_Game_someFunction(JNIEnv * env, jobject obj)
{
pthread_t t;

//Launch a thread
pthread_create(&t, NULL, call_from_thread, NULL);

//Join the thread with the main thread
pthread_join(t, NULL);
}

这是一些 more info关于在 Android 中使用 POSIX 线程。

此外,如果您想在调用 JNI 函数的线程之外的任何线程中使用 JNIEnv 指针,您还需要了解如何将它绑定(bind)到当前线程。来自 JNI 规范:

Creating the VM

The JNI_CreateJavaVM() function loads and initializes a Java VM andreturns a pointer to the JNI interface pointer. The thread that calledJNI_CreateJavaVM() is considered to be the main thread.

Attaching to the VM

The JNI interface pointer (JNIEnv) is valid only in the currentthread. Should another thread need to access the Java VM, it mustfirst call AttachCurrentThread() to attach itself to the VM and obtaina JNI interface pointer. Once attached to the VM, a native threadworks just like an ordinary Java thread running inside a nativemethod. The native thread remains attached to the VM until it callsDetachCurrentThread() to detach itself.

The attached thread should have enough stack space to perform areasonable amount of work. The allocation of stack space per thread isoperating system-specific. For example, using pthreads, the stack sizecan be specified in the pthread_attr_t argument to pthread_create.

Detaching from the VM

A native thread attached to the VM must call DetachCurrentThread() todetach itself before exiting. A thread cannot detach itself if thereare Java methods on the call stack.

关于android - 如何从 JNI 启动一个新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23872663/

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