Android thread_local解决方案

thread_local Android解决方案

背景:Android的run time不支持thread local storage(TLS),其实是没有实现,Android的run time没有用gnu 的glibc,而是使用Google自己实现的Bionic,很多功能没有实现,留了空接口。根据维基百科上的说法,Bionic没实现的还不止这个。比起glibc而言不支持的功能还有:

  • 不支持异常处理
  • 无标准模板(可以用gnustl或者stlport代替)
  • 不支持宽字符
    目前的解决方案有两个,一个是在TLS的地方排除Android平台
    另外一个是使用pthread_getspecificpthread_setspecific进行曲线救国

相关函数详解

在单线程程序中,经常要用到“全局变量”以实现多个函数间共享数据。在多线程环境下由于数据空间是共享的,因此全局变量也为所有线程所共有。但在程序设计中有必要提供线程私有的全局变量,仅在某个线程中生效,但却可以跨多个函数访问,比如程序可能需要每个线程维护一个链表,但是使用相同的函数操作,最简单的方法就是使用同名而不同变量地址的线程相关数据结构。这样的数据结构可以由Posix线程库维护,称为线程私有数据(Thread-specific Data,或TSD)

创建和注销

int pthread_key_create(pthread_key_t *key,void (*destr_function) (void *))
该函数从TSD池中分配一项,将其值赋给key供以后访问使用。如果destr_function不为空,在线程退出(pthread_exit())时将以key所关联的数据为参数调用destr_function(),以释放分配的缓冲区。

不论哪个线程调用pthread_key_create(),所创建的key都是所有线程可以访问的,但各个线程可根据自己的需要往key中填不同的值,这就相当于同名而不同值的全局变量。在LinuxThreads的实现中,TSD池用一个结构数组表示:
static struct pthread_key_struct pthread_keys[PTHREAD_KEYS_MAX] = { {0,NULL} };
创建一个TSD就相当于将结构数组中的某一项设置为“in_use”,并将其索引返回给*key,然后设置destructor函数为destr_function.
注销一个TSD采用如下API:
int pthread_key_delete(pthread_key_t key)
这个函数并不检查当前是否有线程正使用该TSD,也不会调用清理函数(destr_function),而只是将TSD释放以供下一次调用pthread_key_create()使用。在LinuxThreads中,它还会将与之相关的线程数据项设置为NULL。

访问

TSD的读写通过专门的POSIX Thread函数进行,其API定义如下:
int pthread_setspecific(pthread_key_t key,const void *pointer)
void *pthread_getspecific(pthread_key_t key)
写入(pthread_setspecific())时,将pointer的值(不知所指内容)与key相关联,而相应的读出函数则将key相关联的数据读出来。数据类型都是void *,因此可以指向任何类型的数据。
在LinuxThreads中,使用了一个位于线程描述结构(_pthread_descr_struct)中的二维void *指针数组来存放与key相关联的数据,数组大小由以下几个宏来说明:

 #define PTHREAD_KEY_2NDLEVEL_SIZE       32
 #define PTHREAD_KEY_1STLEVEL_SIZE   \
((PTHREAD_KEYS_MAX + PTHREAD_KEY_2NDLEVEL_SIZE - 1)
/ PTHREAD_KEY_2NDLEVEL_SIZE)
    其中在/usr/include/bits/local_lim.h中定义了PTHREAD_KEYS_MAX为1024,
    因此一维数组大小为32。而具体存放的位置由key值经过以下计算得到:
idx1st = key / PTHREAD_KEY_2NDLEVEL_SIZE
idx2nd = key % PTHREAD_KEY_2NDLEVEL_SIZE

也就是说,数据存放在一个32*32的稀疏矩阵中。同样访问的时候也由key值经过类似计算得到数据所在位置索引,再取出其中内容返回

使用范例

使用这一机制达到存储线程私有数据的目的

#include <stdio.h>
#include <pthread.h>
pthread_key_t   key;
void echomsg(int t)
{
        printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);
}
void *child1(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        sleep(2);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
}
void *child2(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        sleep(1);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
}
int main()
{
        int tid1,tid2;
        printf("hello\n");
        pthread_key_create(&key,echomsg);
        pthread_create(&tid1,NULL,child1,NULL);
        pthread_create(&tid2,NULL,child2,NULL);
        sleep(10);
        pthread_key_delete(key);
        printf("main thread exit\n");
        return 0;
}

给例程创建两个线程分别设置同一个线程私有数据为自己的线程ID,为了检验其私有性,程序错开了两个线程私有数据的写入和读出的时间,从程序运行结果可以看出,两个线程对TSD的修改互不干扰。同时,当线程退出时,清理函数会自动执行,参数为tid。

跨平台相关设置

...省略不相关
#ifdef ANDROID
// 在创建线程之前进行局部存储变量的创建
	static pthread_key_t THREAD_LOCAL = 0;
	if (!THREAD_LOCAL)
	{
		pthread_key_create(&THREAD_LOCAL, NULL);
	}
#endif // ANDROID
// 创建线程
	if(pthread_create(&(m_pThreadData->m_thread), &attr, func, arg) == 0)
	{
		m_pThreadData->m_bFinished = FALSE;
	}
...省略不相关

#ifdef WIN32
__declspec( thread ) int _tid = -1;
#else
//__thread int _tid = -1;
thread_local int _tid = -1;
#endif
``

int _tid = 1;
pthread_setspecific(key,(void *)&_tid);
pthread_setspecific(key,(void *)&_tid);
pthread_setspecific(key,(void *)&_tid);
int res = (int)pthread_getspecific(key); // res 3

// 初始化
#ifdef ANDROID
pthread_key_t tid_key;
pthread_key_t vao_key;
pthread_key_t ibo_key;
pthread_key_t vbo_key;
pthread_once_t once_control = PTHREAD_ONCE_INIT;

void once_init()
{
pthread_key_create(&tid_key, NULL);
pthread_key_create(&vao_key, NULL);
pthread_key_create(&ibo_key, NULL);
pthread_key_create(&vbo_key, NULL);
}
#endif

#ifdef ANDROID
pthread_once(&once_control, once_init);
#endif
// 赋初值
int _tid = -1;
GLuint _vao = 0;
GLuint _ibo = 0;
GLuint _vbo = 0;
pthread_setspecific(tid_key, (void *)&_tid);
pthread_setspecific(vao_key, (void *)&_vao);
pthread_setspecific(ibo_key, (void *)&_ibo);
pthread_setspecific(vbo_key, (void *)&_vbo);
// 取值
#ifdef ANDROID
int *_tid = (int *)pthread_getspecific(tid_key);
int errorno = *_tid;
#endif

一个key只可对应保存一种值。若要保存多个线程局部变量,可使用多个key。注意该函数第二个参数接收的是指针,这样才可动态为该变量设值

另附博客:
Linux线程私有数据详解

猜你喜欢

转载自blog.csdn.net/gaoyz1/article/details/83513194
今日推荐