1.当多个线程共享一个变量时,将该变量定义为静态或外部变量,使用互斥量确保共享变量的安全访问。
如果每个线程都需要一个私有变量值,则该值成为线程的私有数据。程序创建一个键,每个线程独立地设定或得到自己的键值,各线程间私有数据互不影响。
2.建立线程私有数据
int pthread_key_create(pthread_key_t *key,void (*destructor)(void *));
int pthread_key_delete(pthread_key_t key);
int pthread_setspecific(pthread_key_t key,void *value);
void *pthread_getspecific(pthread_key_t key);
私有数据键,若多次创建,会覆盖掉前面创建的键,对应的键值也将永远丢失。
使用pthread_key_delete释放一个私有数据键时,必须保证所有线程都不在持有该键的值。
更好的做法是不释放线程私有数据键,因为线程私有数据键最多可达128个,很少有程序需要这么多的树木,没有必要手动释放。
代码示例如下:
创建数据键,设置键值,获取键值
#include<stdio.h> #include<pthread.h> typedef struct tsd_tag { pthread_t tid; char *string; }tsd_t; pthread_key_t tsd_key; pthread_once_t key_once = PTHREAD_ONCE_INIT; void one_routine(void) { pthread_key_create(&tsd_key,NULL);; } void *thread_routine(void *arg) { pthread_once(&key_once,one_routine); tsd_t *value; value = (tsd_t*)malloc(sizeof(tsd_t)); pthread_setspecific(tsd_key,value); value->tid = pthread_self(); value->string = (char*)arg; value=(tsd_t*)pthread_getspecific(tsd_key); sleep(2); value=(tsd_t*)pthread_getspecific(tsd_key); printf("%s done...\n",value->string); } int main(void) { pthread_t tid1,tid2; pthread_create(&tid1,NULL,thread_routine,"thread 1"); pthread_create(&tid2,NULL,thread_routine,"thread 2"); pthread_exit(NULL); }