Wednesday, April 28, 2010

using JNI in pthread

有人問到為什麼不能在native pthread create出來的 thread "直接" 使用 JNI

在這explain 一下 background

大家知道Thread之間是會shared memory的 (不過stack當然還是自己的)
所以大家寫code 有時會用個global 變數  然後兩三個thread來對這global變數作read/write

不過大概在2000年吧?   ABI (Binary Interface)那時有作一些update 
http://www.sco.com/developers/gabi/2000-07-17/contents.html
主要就是多個TLS - Thread Local Storage
就是讓thread 有自己的global 變數 其他的thread並不會踩到別thread的memory

例如  原本的 int g_is_vm_started;
GCC的話 :  在前面加個 __thread  就變成 thread variable了
__thread int g_is_vm_started;
在這看你自己喜歡的compile怎麼改
http://en.wikipedia.org/wiki/Thread-local_storage

而JNI 也是有用到這東西
所以在call JNI時  VM會去拿TLS裡的pointer  裡面存著vm在這個thread裡的context
如果想看Dalvik的code的話
就是在vm/Jni.c裡的 JNI_ENTER() 這macro裡
( 不過Android上其實並沒有Runtime support TLS
用readelf dump library裡其實並沒有.tdata .tbss的section
上面講的TLS 其實是bionic 裡的pthread 自己作出來的
)


想在pthread create出來的thread裡使用JNI
可以先看這
http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/invocation.html

還有個在pthread裡的ClassLoader的問題
http://groups.google.com/group/android-ndk/browse_thread/thread/7982fdb5892f79fb

No comments: