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...
1011 0
|
9月前
|
存储 安全 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函数的多线程编程中,互斥锁的初始化。
1981 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 *
2018 0
WaitHandle——使用Mutex
替代object加锁方式    使用System.object对象作为线程同步的工具,建立了一个基本的锁机制,确保资源只能同时被一个线程所访问。      但是这个对象不作任何其他用途,知识用于锁机制。
1000 0
|
7月前
|
Python
Mutex
【7月更文挑战第2天】
32 2
Pthread线程使用详解
文中先讲解函数,再运行实例,以及一些注意事项
301 0
pthread_mutex_unlock()出错
pthread_mutex_unlock()出错
167 0
|
C++
【C++ 语言】pthread_mutex_t 互斥锁
【C++ 语言】pthread_mutex_t 互斥锁
297 0

热门文章

最新文章