persistent_cache_util.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) 2013, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #pragma once
  6. #include <limits>
  7. #include <list>
  8. #include "util/mutexlock.h"
  9. namespace ROCKSDB_NAMESPACE {
  10. //
  11. // Simple synchronized queue implementation with the option of
  12. // bounding the queue
  13. //
  14. // On overflow, the elements will be discarded
  15. //
  16. template <class T>
  17. class BoundedQueue {
  18. public:
  19. explicit BoundedQueue(
  20. const size_t max_size = std::numeric_limits<size_t>::max())
  21. : cond_empty_(&lock_), max_size_(max_size) {}
  22. virtual ~BoundedQueue() {}
  23. void Push(T&& t) {
  24. MutexLock _(&lock_);
  25. if (max_size_ != std::numeric_limits<size_t>::max() &&
  26. size_ + t.Size() >= max_size_) {
  27. // overflow
  28. return;
  29. }
  30. size_ += t.Size();
  31. q_.push_back(std::move(t));
  32. cond_empty_.SignalAll();
  33. }
  34. T Pop() {
  35. MutexLock _(&lock_);
  36. while (q_.empty()) {
  37. cond_empty_.Wait();
  38. }
  39. T t = std::move(q_.front());
  40. size_ -= t.Size();
  41. q_.pop_front();
  42. return t;
  43. }
  44. size_t Size() const {
  45. MutexLock _(&lock_);
  46. return size_;
  47. }
  48. private:
  49. mutable port::Mutex lock_;
  50. port::CondVar cond_empty_;
  51. std::list<T> q_;
  52. size_t size_ = 0;
  53. const size_t max_size_;
  54. };
  55. } // namespace ROCKSDB_NAMESPACE