這是個GOMP已知的問題,參見 bug42616, bug52738。如果在非主線程上使用openmp指令或者函數,
會crash。這是因為在android上gomp_thread(libgomp/libgomp.h文件中)函數對於用戶創建的線程返回NULL
#ifdef HAVE_TLS
extern __thread struct gomp_thread gomp_tls_data;
static inline struct gomp_thread *gomp_thread (void)
{
return &gomp_tls_data;
}
#else
extern pthread_key_t gomp_tls_key;
static inline struct gomp_thread *gomp_thread (void)
{
return pthread_getspecific (gomp_tls_key);
}
#endif
參見上附代碼,GOMP 在有無tls時的實現不同:
- 如果有tls,HAVE_TLS defined,使用全局變量跟蹤每個線程狀態
- 反之,線程局部數據通過pthread_setspecific管理
在ndk的早期版本中不支持tls,__thread也沒有,所以HAVE_TLS undefined,所以使用了pthread_setspecific函數
當GOMP創建一個工作線程時,它在gomp_thread_start()(line 72)設置了線程specific數據:
#ifdef HAVE_TLS
thr = &gomp_tls_data;
#else
struct gomp_thread local_thr;
thr = &local_thr;
pthread_setspecific (gomp_tls_key, thr);
#endif
但是,當應用創建一個非主thread時,線程specific數據沒有被設置,所以gomp_thread()函數返回NULL。
這就導致了crash,但是如果支持了tls就不會有這個問題
解決方案有兩個:
- 在每個線程創建時調用以下代碼:
// call this piece of code from App Main UI thread at beginning of the App execution,
// and then again in JNI call that will invoke the OpenMP calculations
void initTLS_2_fix_bug_42616_and_52738() {
extern pthread_key_t gomp_tls_key;
static void * _p_gomp_tls = NULL;
void *ptr = pthread_getspecific(gomp_tls_key);
if (ptr == NULL) {
pthread_setspecific(gomp_tls_key, _p_gomp_tls);
} else {
_p_gomp_tls = ptr;
}
}
- 這篇文章中提供了兩個patch,需要重新編譯gcc
- 使用ndk-10e以后的版本
