linuxtls2.cpp 678 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <pthread.h>
  2. #include <iostream>
  3. #include <unistd.h>
  4. //线程局部存储key
  5. __thread int g_mydata = 99;
  6. void* thread_function1(void* args)
  7. {
  8. while (true)
  9. {
  10. g_mydata ++;
  11. }
  12. return NULL;
  13. }
  14. void* thread_function2(void* args)
  15. {
  16. while (true)
  17. {
  18. std::cout << "g_mydata = " << g_mydata << ", ThreadID: " << pthread_self() << std::endl;
  19. sleep(1);
  20. }
  21. return NULL;
  22. }
  23. int main()
  24. {
  25. pthread_t threadIDs[2];
  26. pthread_create(&threadIDs[0], NULL, thread_function1, NULL);
  27. pthread_create(&threadIDs[1], NULL, thread_function2, NULL);
  28. for(int i = 0; i < 2; ++i)
  29. {
  30. pthread_join(threadIDs[i], NULL);
  31. }
  32. return 0;
  33. }