线程本地存储:pthread_key_t

来源:互联网 发布:mac下载软件怎么删除 编辑:程序博客网 时间:2024/06/04 22:15

一、代码

        pthread_key_t

        pthread_key_create()、pthread_key_delete()

        pthread_setspecific()、pthread_getspecific()

#include <stdlib.h>#include <stdio.h>#include <pthread.h>//step 1static 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;}
二、运行结果



0 0