thread-local.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. g++ -std=c++11 -g -O0 thread-local.cpp -o thread-local
  3. */
  4. #include <stdio.h>
  5. // @see https://linux.die.net/man/3/pthread_create
  6. #include <pthread.h>
  7. // Global thread local int variable.
  8. thread_local int tl_g_nn = 0;
  9. // Global thread local variable object.
  10. class MyClass
  11. {
  12. public:
  13. int tl_nn;
  14. MyClass(int nn) {
  15. tl_nn = nn;
  16. }
  17. };
  18. thread_local MyClass g_obj(0);
  19. thread_local MyClass* gp_obj = new MyClass(0);
  20. thread_local MyClass* gp_obj2 = NULL;
  21. MyClass* get_gp_obj2()
  22. {
  23. if (!gp_obj2) {
  24. gp_obj2 = new MyClass(0);
  25. }
  26. return gp_obj2;
  27. }
  28. void* pfn(void* arg)
  29. {
  30. int tid = (int)(long long)arg;
  31. tl_g_nn += tid;
  32. g_obj.tl_nn += tid;
  33. gp_obj->tl_nn += tid;
  34. get_gp_obj2()->tl_nn += tid;
  35. printf("PFN%d: tl_g_nn(%p)=%d, g_obj(%p)=%d, gp_obj(%p,%p)=%d, gp_obj2(%p,%p)=%d\n", tid,
  36. &tl_g_nn, tl_g_nn, &g_obj, g_obj.tl_nn, &gp_obj, gp_obj, gp_obj->tl_nn,
  37. &gp_obj2, gp_obj2, get_gp_obj2()->tl_nn);
  38. return NULL;
  39. }
  40. int main(int argc, char** argv)
  41. {
  42. pthread_t trd = NULL, trd2 = NULL;
  43. pthread_create(&trd, NULL, pfn, (void*)1);
  44. pthread_create(&trd2, NULL, pfn, (void*)2);
  45. pthread_join(trd, NULL);
  46. pthread_join(trd2, NULL);
  47. tl_g_nn += 100;
  48. g_obj.tl_nn += 100;
  49. gp_obj->tl_nn += 100;
  50. get_gp_obj2()->tl_nn += 100;
  51. printf("MAIN: tl_g_nn(%p)=%d, g_obj(%p)=%d, gp_obj(%p,%p)=%d, gp_obj2(%p,%p)=%d\n",
  52. &tl_g_nn, tl_g_nn, &g_obj, g_obj.tl_nn, &gp_obj, gp_obj, gp_obj->tl_nn,
  53. &gp_obj2, gp_obj2, get_gp_obj2()->tl_nn);
  54. return 0;
  55. }