linux线程私有数据函数(pthread_key_create )

最近做的一个项目中,有这么个需求,系统中使用多线程技术,每个线程访问redis,希望每个线程来保存对redis的一份长链接,而不是每个请求建立一次链接。如果在线程启动之前建立好链接,然后传到线程的私有数据中,可以实现。可是系统的框架封装的实现,无法传入数据,这时可以采用线程的私有数据技术进行储存和获取。

其中,有三个关键的系统API可供调用,分别是:

1、pthread_key_create ,创建一个key,各个线程可以用这个key去读数据和写数据。
2、存储数据,采用pthread_setspecific 
3、获取数据,采用pthread_getspecific

这里转载一个网友给出来的示例:http://blog.csdn.net/lmh12506/article/details/8452700

  1. #include <malloc.h>
  2. #include <pthread.h>
  3. #include <stdio.h>
  4. /* The key used to associate a log file pointer with each thread. */
  5. static pthread_key_t thread_log_key;
  6. /* Write MESSAGE to the log file for the current thread. */
  7. void write_to_thread_log (const char* message)
  8. {
  9. FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);
  10. fprintf (thread_log, “%s\n”, message);
  11. }
  12. /* Close the log file pointer THREAD_LOG. */
  13. void close_thread_log (void* thread_log)
  14. {
  15. fclose ((FILE*) thread_log);
  16. }
  17. void* thread_function (void* args)
  18. {
  19. char thread_log_filename[ 20];
  20. FILE* thread_log;
  21. /* Generate the filename for this thread’s log file. */
  22. sprintf (thread_log_filename, “thread%d. log”, ( int) pthread_self ());
  23. /* Open the log file. */
  24. thread_log = fopen (thread_log_filename, “w”);
  25. /* Store the file pointer in thread-specific data under thread_log_key. */
  26. pthread_setspecific (thread_log_key, thread_log);
  27. write_to_thread_log (“Thread starting.”);
  28. /* Do work here... */
  29. return NULL;
  30. }
  31. int main ()
  32. {
  33. int i;
  34. pthread_t threads[ 5];
  35. /* Create a key to associate thread log file pointers in
  36. thread-specific data. Use close_thread_log to clean up the file
  37. pointers. */
  38. pthread_key_create (&thread_log_key, close_thread_log);
  39. /* Create threads to do the work. */
  40. for (i = 0; i < 5; ++i)
  41. pthread_create (&(threads[i]), NULL, thread_function, NULL);
  42. /* Wait for all threads to finish. */
  43. for (i = 0; i < 5; ++i)
  44. pthread_join (threads[i], NULL);
  45. return 0;
  46. }

猜你喜欢

转载自blog.csdn.net/iot_shun/article/details/80990192
今日推荐