CMS 3D CMS Logo

ReusableObjectHolder.h
Go to the documentation of this file.
1 #ifndef FWCore_Utilities_ReusableObjectHolder_h
2 #define FWCore_Utilities_ReusableObjectHolder_h
3 
4 // -*- C++ -*-
5 //
6 // Package: FWCore/Utilities
7 // Class : ReusableObjectHolder
8 //
63 //
64 // Original Author: Chris Jones
65 // Created: Fri, 31 July 2014 14:29:41 GMT
66 //
67 
68 #include <memory>
69 #include <cassert>
70 #include <atomic>
71 #include "tbb/task.h"
72 #include "tbb/concurrent_queue.h"
73 
74 namespace edm {
75  template <class T>
77  public:
81  assert(0 == iOther.m_outstandingObjects);
82  }
84  assert(0 == m_outstandingObjects);
85  T* item = 0;
86  while (m_availableQueue.try_pop(item)) {
87  delete item;
88  }
89  }
90 
94  void add(std::unique_ptr<T> iItem) {
95  if (0 != iItem) {
96  m_availableQueue.push(iItem.release());
97  }
98  }
99 
103  std::shared_ptr<T> tryToGet() {
104  T* item = 0;
105  m_availableQueue.try_pop(item);
106  if (0 == item) {
107  return std::shared_ptr<T>{};
108  }
109  //instead of deleting, hand back to queue
110  auto pHolder = this;
112  return std::shared_ptr<T>{item, [pHolder](T* iItem) { pHolder->addBack(iItem); }};
113  }
114 
116  template <typename F>
117  std::shared_ptr<T> makeOrGet(F iFunc) {
118  std::shared_ptr<T> returnValue;
119  while (!(returnValue = tryToGet())) {
120  add(std::unique_ptr<T>(iFunc()));
121  }
122  return returnValue;
123  }
124 
128  template <typename FM, typename FC>
129  std::shared_ptr<T> makeOrGetAndClear(FM iMakeFunc, FC iClearFunc) {
130  std::shared_ptr<T> returnValue;
131  while (!(returnValue = tryToGet())) {
132  add(std::unique_ptr<T>(iMakeFunc()));
133  }
134  iClearFunc(returnValue.get());
135  return returnValue;
136  }
137 
138  private:
139  void addBack(T* iItem) {
140  m_availableQueue.push(iItem);
142  }
143 
144  tbb::concurrent_queue<T*> m_availableQueue;
145  std::atomic<size_t> m_outstandingObjects;
146  };
147 
148 } // namespace edm
149 
150 #endif /* end of include guard: FWCore_Utilities_ReusableObjectHolder_h */
tbb::concurrent_queue< T * > m_availableQueue
std::shared_ptr< T > makeOrGet(F iFunc)
If there isn&#39;t an object already available, creates a new one using iFunc.
std::shared_ptr< T > makeOrGetAndClear(FM iMakeFunc, FC iClearFunc)
void add(std::unique_ptr< T > iItem)
ReusableObjectHolder(ReusableObjectHolder &&iOther)
HLT enums.
std::shared_ptr< T > tryToGet()
std::atomic< size_t > m_outstandingObjects
static uInt32 F(BLOWFISH_CTX *ctx, uInt32 x)
Definition: blowfish.cc:281
long double T
def move(src, dest)
Definition: eostools.py:511