您的位置:首页 > 其它

线程本地存储:pthread_key_t

2015-03-25 23:23 316 查看
一、代码

        pthread_key_t

[b]        pthread_key_create()、pthread_key_delete()[/b]

[b]        pthread_setspecific()、pthread_getspecific()
[/b]

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

//step 1
static pthread_key_t g_key;

void* thread_proc(void* arg)
{
int id = pthread_self();

//step 3
pthread_setspecific(g_key, &id);

//step 3
int key = *(int*)pthread_getspecific(g_key);

printf("thread 0x%x id is 0x%x\n", pthread_self(), key);

return NULL;
}

int main(int argc, char* argv[])
{
pthread_t tid[10];
int i;

//step 2
pthread_key_create(&g_key, NULL);

for (i=0;i<10;i++)
pthread_create(&tid[i], NULL, thread_proc, NULL);
for (i=0;i<10;i++)
pthread_join(tid[i], NULL);

//step 2
pthread_key_delete(g_key);

return 0;
}
二、运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: