PThreads.hh 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. /*
  2. * PThreads.hh
  3. *
  4. * Copyright 2002, Emiliano Martin emilianomc@terra.es All rights reserved.
  5. *
  6. * See the COPYING file for the terms of usage and distribution.
  7. */
  8. #ifndef _LOG4CPP_THREADING_PTHREADS_HH
  9. #define _LOG4CPP_THREADING_PTHREADS_HH
  10. #include <log4cpp/Portability.hh>
  11. #include <stdio.h>
  12. #include <pthread.h>
  13. #include <string>
  14. #include <assert.h>
  15. namespace log4cpp {
  16. namespace threading {
  17. /**
  18. * returns the thread ID
  19. **/
  20. std::string getThreadId();
  21. /**
  22. **/
  23. class Mutex {
  24. private:
  25. pthread_mutex_t mutex;
  26. public:
  27. inline Mutex() {
  28. ::pthread_mutex_init(&mutex, NULL);
  29. }
  30. inline void lock() {
  31. ::pthread_mutex_lock(&mutex);
  32. }
  33. inline void unlock() {
  34. ::pthread_mutex_unlock(&mutex);
  35. }
  36. inline ~Mutex() {
  37. ::pthread_mutex_destroy(&mutex);
  38. }
  39. private:
  40. Mutex(const Mutex& m);
  41. Mutex& operator=(const Mutex &m);
  42. };
  43. /**
  44. * definition of ScopedLock;
  45. **/
  46. class ScopedLock {
  47. private:
  48. Mutex& _mutex;
  49. public:
  50. inline ScopedLock(Mutex& mutex) :
  51. _mutex(mutex) {
  52. _mutex.lock();
  53. }
  54. inline ~ScopedLock() {
  55. _mutex.unlock();
  56. }
  57. };
  58. /**
  59. *
  60. **/
  61. template<typename T> class ThreadLocalDataHolder {
  62. private:
  63. pthread_key_t _key;
  64. public:
  65. typedef T data_type;
  66. inline ThreadLocalDataHolder() {
  67. ::pthread_key_create(&_key, freeHolder);
  68. }
  69. inline static void freeHolder(void *p) {
  70. assert(p != NULL);
  71. delete reinterpret_cast<T *>(p);
  72. }
  73. inline ~ThreadLocalDataHolder() {
  74. T *data = get();
  75. if (data != NULL) {
  76. delete data;
  77. }
  78. ::pthread_key_delete(_key);
  79. }
  80. inline T* get() const {
  81. return reinterpret_cast<T *>(::pthread_getspecific(_key));
  82. }
  83. inline T* operator->() const { return get(); }
  84. inline T& operator*() const { return *get(); }
  85. inline T* release() {
  86. T* result = get();
  87. ::pthread_setspecific(_key, NULL);
  88. return result;
  89. }
  90. inline void reset(T* p = NULL) {
  91. T *data = get();
  92. if (data != NULL) {
  93. delete data;
  94. }
  95. ::pthread_setspecific(_key, p);
  96. }
  97. };
  98. }
  99. }
  100. #endif