从线程中返回结果
在上篇的基础上添加pthread_join(), 这个函数将会挂起调用线程,直至创建的线程执行完,这时ret_val返回0.
int pthread_join(pthread_t thread, void** ret_val);
- native-thread.cpp
extern "C"
JNIEXPORT void JNICALL
Java_com_zhuhongxi_nativcethreaddemo1_MainActivity_posixThreads(JNIEnv *env, jobject thiz,
jint threads, jint iterations) {
//线程句柄
pthread_t *handles = new pthread_t[threads];
//为每一个worker创建一个posix线程去执行
for (jint i = 0; i < threads; i++) {
//组装每一个worker参数
NativeWorkerArgs *nativeWorkerArgs = new NativeWorkerArgs();
nativeWorkerArgs->id = i;
nativeWorkerArgs->iteration = iterations;
//创建pthread
pthread_t thread;
int result = pthread_create(&handles[i], nullptr, nativeWorkerThread,
(void *) nativeWorkerArgs);
//如果创建失败就抛出一个java异常
if (0 != result) {
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to create native thread");
goto exit;
}
}
for (int i = 0; i < threads; ++i) {
void* result = nullptr;
if (0 != pthread_join(handles[i], &result))
{
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to join thread");
}
else
{
char message[26];
sprintf(message, "Worker %d: Iteration %d", i, result);
//新建一个字符串
jstring messageString = env->NewStringUTF(message);
//调用java中的回调方法
env->CallVoidMethod(gObj, gOnNativeMessage, messageString);
if (nullptr != env->ExceptionOccurred())
{
goto exit;
}
}
}
exit:
return;
}