openmp 在android上crash的解决方案

这是个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就不会有这个问题
解决方案有两个:

  1. 在每个线程创建时调用以下代码:
// 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;
	}
}
  1. 这篇文章中提供了两个patch,需要重新编译gcc
  2. 使用ndk-10e以后的版本
posted @ 2016-10-09 16:52  Lcnoctave  阅读(2167)  评论(0编辑  收藏  举报