diobjcou.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /*
  2. *
  3. * Copyright (C) 1996-2011, OFFIS e.V.
  4. * All rights reserved. See COPYRIGHT file for details.
  5. *
  6. * This software and supporting documentation were developed by
  7. *
  8. * OFFIS e.V.
  9. * R&D Division Health
  10. * Escherweg 2
  11. * D-26121 Oldenburg, Germany
  12. *
  13. *
  14. * Module: dcmimgle
  15. *
  16. * Author: Joerg Riesmeier
  17. *
  18. * Purpose: DicomObjectCounter (Header)
  19. *
  20. */
  21. #ifndef DIOBJCOU_H
  22. #define DIOBJCOU_H
  23. #include "dcmtk/config/osconfig.h"
  24. #ifdef WITH_THREADS
  25. #include "dcmtk/ofstd/ofthread.h"
  26. #endif
  27. #include "dcmtk/dcmimgle/didefine.h"
  28. /*---------------------*
  29. * class declaration *
  30. *---------------------*/
  31. /** Class to count number of instances (objects created from a certain class).
  32. * used to manage more than one reference to an object in a secure way.
  33. */
  34. class DCMTK_DCMIMGLE_EXPORT DiObjectCounter
  35. {
  36. public:
  37. /** add a reference.
  38. * Increase the internal counter by 1.
  39. */
  40. inline void addReference()
  41. {
  42. #ifdef WITH_THREADS
  43. theMutex.lock();
  44. #endif
  45. ++Counter;
  46. #ifdef WITH_THREADS
  47. theMutex.unlock();
  48. #endif
  49. }
  50. /** remove a reference.
  51. * Decrease the internal counter by 1 and delete the object only if the counter is zero.
  52. */
  53. inline void removeReference()
  54. {
  55. #ifdef WITH_THREADS
  56. theMutex.lock();
  57. #endif
  58. if (--Counter == 0)
  59. {
  60. #ifdef WITH_THREADS
  61. theMutex.unlock();
  62. #endif
  63. delete this;
  64. #ifdef WITH_THREADS
  65. } else {
  66. theMutex.unlock();
  67. #endif
  68. }
  69. }
  70. protected:
  71. /** constructor.
  72. * Internal counter is initialized with 1.
  73. */
  74. DiObjectCounter()
  75. : Counter(1)
  76. #ifdef WITH_THREADS
  77. ,theMutex()
  78. #endif
  79. {
  80. }
  81. /** destructor
  82. */
  83. virtual ~DiObjectCounter()
  84. {
  85. }
  86. private:
  87. /// internal counter
  88. unsigned long Counter;
  89. #ifdef WITH_THREADS
  90. /** if compiled for multi-thread operation, the Mutex protecting
  91. * access to the value of this object.
  92. */
  93. OFMutex theMutex;
  94. #endif
  95. };
  96. #endif