ShmemPool.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  4. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "mozilla/Assertions.h"
  6. #include "mozilla/Logging.h"
  7. #include "mozilla/ShmemPool.h"
  8. #include "mozilla/Move.h"
  9. namespace mozilla {
  10. ShmemPool::ShmemPool(size_t aPoolSize)
  11. : mMutex("mozilla::ShmemPool"),
  12. mPoolFree(aPoolSize)
  13. #ifdef DEBUG
  14. ,mMaxPoolUse(0)
  15. #endif
  16. {
  17. mShmemPool.SetLength(aPoolSize);
  18. }
  19. mozilla::ShmemBuffer ShmemPool::GetIfAvailable(size_t aSize)
  20. {
  21. MutexAutoLock lock(mMutex);
  22. // Pool is empty, don't block caller.
  23. if (mPoolFree == 0) {
  24. // This isn't initialized, so will be understood as an error.
  25. return ShmemBuffer();
  26. }
  27. ShmemBuffer& res = mShmemPool[mPoolFree - 1];
  28. if (!res.mInitialized) {
  29. LOG(("No free preallocated Shmem"));
  30. return ShmemBuffer();
  31. }
  32. MOZ_ASSERT(res.mShmem.IsWritable(), "Pool in Shmem is not writable?");
  33. if (res.mShmem.Size<char>() < aSize) {
  34. LOG(("Free Shmem but not of the right size"));
  35. return ShmemBuffer();
  36. }
  37. mPoolFree--;
  38. #ifdef DEBUG
  39. size_t poolUse = mShmemPool.Length() - mPoolFree;
  40. if (poolUse > mMaxPoolUse) {
  41. mMaxPoolUse = poolUse;
  42. LOG(("Maximum ShmemPool use increased: %d buffers", mMaxPoolUse));
  43. }
  44. #endif
  45. return Move(res);
  46. }
  47. void ShmemPool::Put(ShmemBuffer&& aShmem)
  48. {
  49. MutexAutoLock lock(mMutex);
  50. MOZ_ASSERT(mPoolFree < mShmemPool.Length());
  51. mShmemPool[mPoolFree] = Move(aShmem);
  52. mPoolFree++;
  53. #ifdef DEBUG
  54. size_t poolUse = mShmemPool.Length() - mPoolFree;
  55. if (poolUse > 0) {
  56. LOG(("ShmemPool usage reduced to %d buffers", poolUse));
  57. }
  58. #endif
  59. }
  60. ShmemPool::~ShmemPool()
  61. {
  62. #ifdef DEBUG
  63. for (size_t i = 0; i < mShmemPool.Length(); i++) {
  64. MOZ_ASSERT(!mShmemPool[i].Valid());
  65. }
  66. #endif
  67. }
  68. } // namespace mozilla