Dear friends,
I have successfully integrated native (C++) codes which employ threading operation with a simple java program. The objective of the program is to spawn thread (using POSIX pthread_create) that prints 10 “Hello World” in approx. 10 seconds.
My Software environment JBuilder9 (jdk1.4) in Linux 7.2
I have created a shared library A shared library libhelloworld.so (g++ using native CJNI_Layer.cpp & CNative.cpp) is created.
Running the application java CJNI_Layer
Java Program Output Native thread prints “Hello World” 10 times (in approx. 10 seconds) before returning to Java program (CJNI_Layer.java)
Seems that I have achieved what I wanted. However, a closer look at the java program depicts that the thread should terminate and exit way before the Native Method ThreadFunction() completes its execution of printing 10 “Hello World”. This is because the java program (main process) should have exited before the native method completes execution.
It appears to me that the native thread has seized the entire flow of control from java program and it is not running independently. Why is that so? How can I make the native thread independent and not seize the flow of control from the java program? I would really appreciate if you can my answer my questions. Thank you very much.
JJ
--- CJNI_Layer.java --- class CJNI_Layer { static { try { System.loadlibrary(“helloworld”); } catch (UnsatisfiedLinkError ule) { System.out.println(ule); } }
private native int SpawnThread();
public static void main(String args []) { CJNI_Layer c = new CJNI_Layer();
c.SpawnThread(); } }
--- CJNI_Layer.cpp --- #include CJNI_Layer.h // generated by javah #include “CNative.h” // defines structure of Class CNative
JNIEXPORT jint JNICALL Java_CJNI_Layer_ SpawnThread(JNIEnv *, jobject) { CNative native_class; // an array of CNative native_class.SpawnThread(); return 0; }
--- CNative.cpp --- native implementation in C++ #include <unistd.h> #include <stdio.h> #include “CNative.h”
void *thread_func(void *p) // this function is declared as a friend to CNative in CNative.h { CNative *pCNative = reinterpret_cast<CNative *>(p); If(pCNative) pCNative->ThreadFunction(); return 0; }
void CNative::ThreadFunction() { for (int i = 0; i < 10; i++){ printf(“\nHello World”); sleep(1); } return; }
int CNative::SpawnThread() { int res = pthread_create(&thread, NULL, thread_func, this); // protected class member pthread_t thread return res; }
|
- Re: JNI Multithread Question in Linux Kok Choon Kiat
- Re: JNI Multithread Question in Linux Paul Mclachlan
- Re: JNI Multithread Question in Linux Neal Sanche