我做了一个例子,它创建了一个 pthread 来打印一条消息。但是输出是出乎意料的。
代码:
System.out.println("Before call native thread");
// invoke the native method to print a message
int socketId = new SocketJNI().createSocket(); //line 7
Thread.sleep(2000);
System.out.println("After call native thread");//line 9: create break point here
C代码:
JNIEXPORT jint JNICALL
Java_SocketJNI_createSocket(JNIEnv * env, jobject obj)
{
pthread_t thread;
pthread_create(&thread, NULL, createSocket, NULL);
return 0;
}
void* createSocket(void *arg)
{
printf("Inside native thread(pthread)");
pthread_exit(NULL);
}
输出:
Before call native thread
After call native thread
Inside native thread(pthread)
但我认为应该是:
Before call native thread
Inside native thread(pthread)
After call native thread
那么,问题是什么?pthread 是如何工作的?
更新:
当我到达第 8 行(调试)时,pthread(在第 7 行创建)不打印消息,它只打印:
Before call native thread
我等待,等待但不是打印第 9 行之后的内容:
Before call native thread
After call native thread