singleton_pool.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // "$Id$"
  3. //
  4. // Copyright (c)1992-2007, ZheJiang Dahua Technology Stock CO.LTD.
  5. // All Rights Reserved.
  6. //
  7. // Description:
  8. // Revisions: Year-Month-Day SVN-Author Modification
  9. //
  10. #ifndef DAHUA_MEMORY_DETAIL_POOL_H__
  11. #define DAHUA_MEMORY_DETAIL_POOL_H__
  12. // std::less, std::less_equal, std::greater
  13. #include <functional>
  14. // std::size_t, std::ptrdiff_t
  15. #include <cstddef>
  16. // std::max
  17. #include <algorithm>
  18. #include "singleton.h"
  19. #ifndef DAHUA_PREVENT_MACRO_SUBSTITUTION
  20. #define DAHUA_PREVENT_MACRO_SUBSTITUTION
  21. #endif
  22. namespace Dahua {
  23. namespace Memory {
  24. namespace Detail {
  25. ////////////////////////////////////////////////////////////////////////////////
  26. /// Ḭ̈߳²È«µÄµ¥¼þÄÚ´æ³Ø
  27. template <typename Tag, unsigned requestedSize,
  28. typename Pool,
  29. typename Mutex,
  30. unsigned nextSize,
  31. unsigned maxSize>
  32. struct singleton_pool
  33. {
  34. public:
  35. typedef Tag tag;
  36. typedef Pool pool_type;
  37. typedef Mutex mutex_type;
  38. typedef size_t size_type;
  39. typedef std::ptrdiff_t difference_type;
  40. static const unsigned requested_size = requestedSize;
  41. static const unsigned next_size = nextSize;
  42. private:
  43. struct mem_pool : Mutex
  44. {
  45. pool_type p;
  46. mem_pool() : p(requestedSize, nextSize) {}
  47. };
  48. struct guard
  49. {
  50. Mutex& m;
  51. guard(Mutex& mutex) : m(mutex) {m.lock();}
  52. ~guard() {m.unlock();}
  53. };
  54. typedef singleton_default<mem_pool> singleton;
  55. singleton_pool();
  56. public:
  57. static void * malloc DAHUA_PREVENT_MACRO_SUBSTITUTION()
  58. {
  59. mem_pool & p = singleton::instance();
  60. guard g(p);
  61. return (p.p.malloc)();
  62. }
  63. static void free DAHUA_PREVENT_MACRO_SUBSTITUTION(void * const ptr)
  64. {
  65. mem_pool & p = singleton::instance();
  66. guard g(p);
  67. (p.p.free)(ptr);
  68. }
  69. };
  70. } // namespace Detail
  71. } // namespace Memory
  72. } // namespace Dahua
  73. #endif // DAHUA_MEMORY_DETAIL_POOL_H__