MemoryPool.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. //
  2. // MemoryPool.h
  3. //
  4. // $Id: //poco/1.4/Foundation/include/Poco/MemoryPool.h#1 $
  5. //
  6. // Library: Foundation
  7. // Package: Core
  8. // Module: MemoryPool
  9. //
  10. // Definition of the MemoryPool class.
  11. //
  12. // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
  13. // and Contributors.
  14. //
  15. // SPDX-License-Identifier: BSL-1.0
  16. //
  17. #ifndef Foundation_MemoryPool_INCLUDED
  18. #define Foundation_MemoryPool_INCLUDED
  19. #include "Poco/Foundation.h"
  20. #include "Poco/Mutex.h"
  21. #include <vector>
  22. #include <cstddef>
  23. namespace Poco {
  24. class Foundation_API MemoryPool
  25. /// A simple pool for fixed-size memory blocks.
  26. ///
  27. /// The main purpose of this class is to speed-up
  28. /// memory allocations, as well as to reduce memory
  29. /// fragmentation in situations where the same blocks
  30. /// are allocated all over again, such as in server
  31. /// applications.
  32. ///
  33. /// All allocated blocks are retained for future use.
  34. /// A limit on the number of blocks can be specified.
  35. /// Blocks can be preallocated.
  36. {
  37. public:
  38. MemoryPool(std::size_t blockSize, int preAlloc = 0, int maxAlloc = 0);
  39. /// Creates a MemoryPool for blocks with the given blockSize.
  40. /// The number of blocks given in preAlloc are preallocated.
  41. ~MemoryPool();
  42. void* get();
  43. /// Returns a memory block. If there are no more blocks
  44. /// in the pool, a new block will be allocated.
  45. ///
  46. /// If maxAlloc blocks are already allocated, an
  47. /// OutOfMemoryException is thrown.
  48. void release(void* ptr);
  49. /// Releases a memory block and returns it to the pool.
  50. std::size_t blockSize() const;
  51. /// Returns the block size.
  52. int allocated() const;
  53. /// Returns the number of allocated blocks.
  54. int available() const;
  55. /// Returns the number of available blocks in the pool.
  56. private:
  57. MemoryPool();
  58. MemoryPool(const MemoryPool&);
  59. MemoryPool& operator = (const MemoryPool&);
  60. enum
  61. {
  62. BLOCK_RESERVE = 128
  63. };
  64. typedef std::vector<char*> BlockVec;
  65. std::size_t _blockSize;
  66. int _maxAlloc;
  67. int _allocated;
  68. BlockVec _blocks;
  69. FastMutex _mutex;
  70. };
  71. //
  72. // inlines
  73. //
  74. inline std::size_t MemoryPool::blockSize() const
  75. {
  76. return _blockSize;
  77. }
  78. inline int MemoryPool::allocated() const
  79. {
  80. return _allocated;
  81. }
  82. inline int MemoryPool::available() const
  83. {
  84. return (int) _blocks.size();
  85. }
  86. } // namespace Poco
  87. #endif // Foundation_MemoryPool_INCLUDED