多线程变量 pthread_key_t 自查文档
2016-05-19 16:29
344 查看
相关接口:
eg:\
/article/8304809.html
/article/10629330.html
#include <pthread.h> // init_routine函数在多线程环境中只执行一次 int pthread_once(pthread_once_t *once_control, void (*init_routine)(void)); pthread_once_t once_control = PTHREAD_ONCE_INIT; //新建 key,一个key只能执行一次. destructor为删除key释放处理函数。如果为空采用系统默认方式 int pthread_key_create(pthread_key_t *key, void (*destructor)(void*)); int pthread_key_delete(pthread_key_t key); void *pthread_getspecific(pthread_key_t key); int pthread_setspecific(pthread_key_t key, const void *value);
eg:\
#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> //atexit using namespace std; pthread_key_t key; pthread_once_t thread_once = PTHREAD_ONCE_INIT; void echomsg(void *); void once_run(void) { printf("pthread_key_t init in the once_run\n "); pthread_key_create(&key,echomsg); } void echomsg(void* p) { int t=*(int*)p; printf( "destructor excuted in thread %d, param=%d\n ",pthread_self(),t); delete (int *)p; } void* child1(void* arg) { int*ptid= new int; pthread_once(&thread_once, once_run);//测试pthread_once是否还会在此执行不,因为在main线程已经执行了. *ptid=pthread_self(); printf( "thread1 %d enter\n ",*ptid); pthread_setspecific(key,(void*)ptid); sleep(2); printf( "thread1 %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key))); sleep(5); pthread_exit(NULL); return NULL; } void* child2(void* arg) { int*ptid= new int; *ptid=pthread_self(); printf( "thread2 %d enter\n ",*ptid); pthread_setspecific(key,(void*)ptid); sleep(1); printf( "thread2 %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key))); sleep(1); pthread_exit(NULL); return NULL; } void main_exit() { pthread_key_delete(key); } int main() { pthread_t tid1,tid2; printf( "hello\n "); atexit(main_exit);//为了防止sleep(4)放到pthread_key_delete(key)后面就会出现段错误了。但是个人也不很提倡用atexit这个函数。 pthread_once(&thread_once, once_run); //pthread_key_create(&key,echomsg); //保证一次性运行把其放到了pthread_once了 pthread_create(&tid1,NULL,child1,NULL); pthread_create(&tid2,NULL,child2,NULL); //pthread_join(tid1,NULL); //pthread_join(tid2,NULL); sleep(10); //pthread_key_delete(key); printf( "main thread %d exit\n ",pthread_self()); return 0; }
/article/8304809.html
/article/10629330.html
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- android listview 连续调用getview问题分析及解决
- Android 4.0 事件输入(Event Input)系统
- 【Maven】maven的常用命令以及搭建maven私人仓库
- GeekBand第二周 ListView(上)
- SM2算法第十四篇:ECDH秘钥交换的C程序
- SHELL跳出循环、shift左移、函数的使用和数据库自动备份脚本
- Ruby程序中正则表达式的基本使用教程
- JAVA:借用OpenOffice将上传的Word文档转换成Html格式
- [Book Note] Haskell: Monad
- WebSphere MQ简单的命令行操作
- POJ 2096 Collecting Bugs
- JAVA jdk 线程池学习笔记
- win下部署solr4.7.2
- Leetcode 326 Power of Three
- U盘中毒文件都不见了
- linux查看磁盘是否SSD盘
- 利用log4j显示hibernate打印sql中的参数
- G-CNN: an Iterative Grid Based Object Detector
- UICollectionView使用方法