Linux线程私有数据
来源:互联网 发布:棉麻旗袍 知乎专栏 编辑:程序博客网 时间:2024/05/02 00:12
最近做的一个项目中,有这么个需求,系统中使用多线程技术,每个线程访问redis,希望每个线程来保存对redis的一份长链接,而不是每个请求建立一次链接。如果在线程启动之前建立好链接,然后传到线程的私有数据中,可以实现。可是系统的框架封装的实现,无法传入数据,这时可以采用线程的私有数据技术进行储存和获取。
其中,有三个关键的系统API可供调用,分别是:
1、pthread_key_create ,创建一个key,各个线程可以用这个key去读数据和写数据。
2、存储数据,采用pthread_setspecific
3、获取数据,采用pthread_getspecific
这里转载一个网友给出来的示例:http://blog.csdn.net/lmh12506/article/details/8452700
#include <malloc.h>#include <pthread.h>#include <stdio.h>/* The key used to associate a log file pointer with each thread. */static pthread_key_t thread_log_key;/* Write MESSAGE to the log file for the current thread. */void write_to_thread_log (const char* message){FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);fprintf (thread_log, “%s\n”, message);}/* Close the log file pointer THREAD_LOG. */void close_thread_log (void* thread_log){fclose ((FILE*) thread_log);}void* thread_function (void* args){char thread_log_filename[20];FILE* thread_log;/* Generate the filename for this thread’s log file. */sprintf (thread_log_filename, “thread%d.log”, (int) pthread_self ());/* Open the log file. */thread_log = fopen (thread_log_filename, “w”);/* Store the file pointer in thread-specific data under thread_log_key. */pthread_setspecific (thread_log_key, thread_log);write_to_thread_log (“Thread starting.”);/* Do work here... */return NULL;}int main (){int i;pthread_t threads[5];/* Create a key to associate thread log file pointers inthread-specific data. Use close_thread_log to clean up the filepointers. */pthread_key_create (&thread_log_key, close_thread_log);/* Create threads to do the work. */for (i = 0; i < 5; ++i)pthread_create (&(threads[i]), NULL, thread_function, NULL);/* Wait for all threads to finish. */for (i = 0; i < 5; ++i)pthread_join (threads[i], NULL);return 0;}
0 0
- linux线程私有数据
- linux线程私有数据
- Linux线程私有数据
- Linux线程私有数据pthread_key_t
- linux线程私有数据详解
- linux线程的私有数据
- linux线程的私有数据
- linux线程私有数据的保护
- Linux高级程序设计----线程与私有数据
- linux 线程私有数据 (一键多值)
- Linux学习笔记:线程私有数据
- 【Linux系统编程】线程私有数据
- linux线程之线程私有数据 pthread_key_create方法的学习
- 线程的私有数据
- 线程与私有数据
- Posix线程私有数据
- 线程私有数据
- 线程私有数据
- BZOJ 3893 Usaco2014 Dec Cow Jog 模拟
- 山楂果脯
- 【BZOJ3891】【Usaco2014 Dec】Piggy Back bfs+动规?
- AFNetworking 文件上传Data,File图片,文件等上传
- iOS GCD使用指南
- Linux线程私有数据
- [Cocos2d塔防游戏开发]Cocos2dx-3.X完成塔防游戏《王国保卫战》--简介+代码+资源
- 设置EXCEL表某列的宽度
- 数论专题小结:素数筛法
- rails时间转换
- POJ 2236 Wireless Network
- tomcat7 设置用户名和密码 roles设置内容与以往的不同
- iOS学习4:UITextView的用法及技巧(ios7下光标bug解决方案)
- android培训、java培训、java学习型技