線程特定數據
作用
定義:存儲和查詢特定線程相關數據的一種機制
-
線程共享進程的存儲空間,而我們希望每個線程訪問自己的數據
-
通過線程特定數據的機制,線程特定數據操作函數可以提高線程間的數據獨立性
流程
創建與線程特定數據關聯的鍵
pthread_key_create(pthread_key_t keyp,void(destructor)(void ));
通過pthread_key_delete(pthread_key_t)刪除鍵與線程特定數據關聯
有些線程可能看到一個鍵值,而其他線程可能看到是另一個不同的鍵,這取決於系統如何調度
,解決這種競爭的辦法是使用pthread_once
pthread_once_t initflag = PTHREAD_ONCE_INIT;
pthread_once(&initflag,void (initfn)(void));
initflag必須非局部變量,必須初始化爲PTHREAD_ONCE_INIT;
thread_init(void)
{
phtread_key_create(&key,destructor);
}
thread_func(void arg){
pthread_once(&initflag,thread_init)
pthread_setspecific(key,const void value)//設置私有數據
pthread_getspecial(key);//獲取
}
測試程序
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
static pthread_key_t key;
static pthread_once_t initflag;
thread_init(void){
pthread_key_create(&key,NULL);//清理函數未設置
}
void func(void arg)
{
pthread_once(&initflag,thread_init);
char *buf = (char*)malloc(100);
char *p ;
memset(buf,0,100);
sprintf(buf,"%s%d","hello",(int)arg);
pthread_setspecific(key,buf);
p=(void*)pthread_getspecific(key);
printf("func:phtread_self %ld %s\n",pthread_self(),p);
//刪除key與線程特定空間的聯繫
return NULL;
}
int main()
{
pthread_t tid,tid1;
pthread_create(&tid,NULL,func,(void*)1);
pthread_create(&tid1,NULL,func,(void*)2);
pthread_join(tid,NULL);
pthread_join(tid1,NULL);
return 0;
}
輸出結果
func:phtread_self 139704569833216 hello2
func:phtread_self 139704578225920 hello1