Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. #ifndef __PER_THREAD_H__
  2. #define __PER_THREAD_H__
  3.  
  4. #include <assert.h>
  5. #include <pthread.h>
  6.  
  7. template <typename T>
  8. class PerThread
  9. {
  10. public:
  11. PerThread()
  12. {
  13. assert(pthread_key_create(&m_oKey, destructor) == 0);
  14. }
  15. ~PerThread()
  16. {
  17. (void)pthread_key_delete(m_oKey);
  18. }
  19.  
  20. T& Get()
  21. {
  22. T *value = (T*)pthread_getspecific(m_oKey);
  23. if (value == NULL)
  24. {
  25. value = new T();
  26. assert(value);
  27. assert(pthread_setspecific(m_oKey, value) == 0);
  28. }
  29. return *value;
  30. }
  31.  
  32. private:
  33. static void destructor(void *value)
  34. {
  35. if (value != NULL)
  36. delete (T*)value;
  37. }
  38.  
  39. private:
  40. pthread_key_t m_oKey;
  41. };
  42.  
  43. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement