pthread_getspecific和pthread_setspecific使用

简介:

#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,如需转载请自行联系原作者

相关文章
|
数据处理
pthread
设置进程绑定状态的函数pthread_attr_setscopepthread_attr_t 指向属性结构的指针第二个参数 绑定类型 pthread_scope_system()pthread_scope_process(非绑定)创建一个绑定线程 线程属性结构pthread_attr_t #in...
1016 0
|
10月前
|
存储 安全 NoSQL
pthread_getspecific和pthread_setspecific详解
pthread_getspecific和pthread_setspecific详解
|
Linux API
pthread_mutex_init & 互斥锁pthread_mutex_t的使用
pthread_mutex_init l         头文件: #include l         函数原型: int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; l         函数作用: 该函数用于C函数的多线程编程中,互斥锁的初始化。
1991 0
2线程原语:pthread_create(),pthread_self(),pthread_exit(),pthread_join(),pthread_cancel(),pthread_detach(
 1 pthread_create()函数 创建线程 A:依赖的头文件 #include&lt;pthread.h&gt; B:函数声明 int pthread_create(pthread_t *thread, constpthread_attr_t *attr, void *(*start_routine) (void *), void *
2025 0
Pthread线程使用详解
文中先讲解函数,再运行实例,以及一些注意事项
342 0
|
调度 索引
pthread_rwlock_t读写锁函数说明
转:http://www.cnblogs.com/renxinyuan/p/3875659.html 索引:  初始化一个读写锁pthread_rwlock_init 读锁定读写锁      pthread_rwlock_rdlock 非阻塞读锁定  pthread_rwlock_tryr...
1245 0
|
8月前
|
Python
Mutex
【7月更文挑战第2天】
36 2
WaitHandle——使用Mutex
替代object加锁方式    使用System.object对象作为线程同步的工具,建立了一个基本的锁机制,确保资源只能同时被一个线程所访问。      但是这个对象不作任何其他用途,知识用于锁机制。
1000 0