linuxtls.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. //线程局部存储key
  5. pthread_key_t thread_log_key;
  6. void write_to_thread_log(const char* message)
  7. {
  8. if (message == NULL)
  9. return;
  10. FILE* logfile = (FILE*)pthread_getspecific(thread_log_key);
  11. fprintf(logfile, "%s\n", message);
  12. fflush(logfile);
  13. }
  14. void close_thread_log(void* logfile)
  15. {
  16. char logfilename[128];
  17. sprintf(logfilename, "close logfile: thread%ld.log\n", (unsigned long)pthread_self());
  18. printf(logfilename);
  19. fclose((FILE *)logfile);
  20. }
  21. void* thread_function(void* args)
  22. {
  23. char logfilename[128];
  24. sprintf(logfilename, "thread%ld.log", (unsigned long)pthread_self());
  25. FILE* logfile = fopen(logfilename, "w");
  26. if (logfile != NULL)
  27. {
  28. pthread_setspecific(thread_log_key, logfile);
  29. write_to_thread_log("Thread starting...");
  30. }
  31. return NULL;
  32. }
  33. int main()
  34. {
  35. pthread_t threadIDs[5];
  36. pthread_key_create(&thread_log_key, close_thread_log);
  37. for(int i = 0; i < 5; ++i)
  38. {
  39. pthread_create(&threadIDs[i], NULL, thread_function, NULL);
  40. }
  41. for(int i = 0; i < 5; ++i)
  42. {
  43. pthread_join(threadIDs[i], NULL);
  44. }
  45. return 0;
  46. }