且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pthread_getspecific和pthread_setspecific使用

更新时间:2022-09-16 17:32:42

#more test.c

 

/*

 * =====================================================================================

 *       Filename:  thead.c

 *    Description:  getspecific

 *        Created:  05/10/2011 12:09:43 AM

 * =====================================================================================

 */

#include<stdio.h>

#include<pthread.h>

#include<string.h>

pthread_key_t p_key;

 

void func1()

{

        int *tmp = (int*)pthread_getspecific(p_key);//同一线程内的各个函数间共享数据。

        printf("%d is runing in %s\n",*tmp,__func__);

 

}

void *thread_func(void *args)

{

 

        pthread_setspecific(p_key,args);

 

        int *tmp = (int*)pthread_getspecific(p_key);//获得线程的私有空间

        printf("%d is runing in %s\n",*tmp,__func__);

 

        *tmp = (*tmp)*100;//修改私有变量的值

 

        func1();

 

        return (void*)0;

}

int main()

{

        pthread_t pa, pb;

        int a=1;

        int b=2;

        pthread_key_create(&p_key,NULL);

        pthread_create(&pa, NULL,thread_func,&a);

        pthread_create(&pb, NULL,thread_func,&b);

        pthread_join(pa, NULL);

        pthread_join(pb, NULL);

        return 0;

}

 

 

#gcc -lpthread  test.c -o test

# ./test 

 

2 is runing in thread_func

1 is runing in thread_func

100 is runing in func1

200 is runing in func1



本文转自莫水千流博客园博客,原文链接:http://www.cnblogs.com/zhoug2020/p/3951352.html,如需转载请自行联系原作者