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 
75 namespace edm {
76  template<class T>
78  public:
83  assert(0== iOther.m_outstandingObjects);
84  }
86  assert(0==m_outstandingObjects);
87  T* item = 0;
88  while( m_availableQueue.try_pop(item)) {
89  delete item;
90  }
91  }
92 
96  void add(std::unique_ptr<T> iItem){
97  if(0!=iItem) {
98  m_availableQueue.push(iItem.release());
99  }
100  }
101 
105  std::shared_ptr<T> tryToGet() {
106  T* item = 0;
107  m_availableQueue.try_pop(item);
108  if (0==item) {
109  return std::shared_ptr<T>{};
110  }
111  //instead of deleting, hand back to queue
112  auto pHolder = this;
114  return std::shared_ptr<T>{item, [pHolder](T* iItem) {pHolder->addBack(iItem);} };
115  }
116 
118  template< typename F>
119  std::shared_ptr<T> makeOrGet( F iFunc) {
120  std::shared_ptr<T> returnValue;
121  while ( ! ( returnValue = tryToGet()) ) {
122  add( std::unique_ptr<T>(iFunc()) );
123  }
124  return returnValue;
125  }
126 
130  template< typename FM, typename FC>
131  std::shared_ptr<T> makeOrGetAndClear( FM iMakeFunc, FC iClearFunc) {
132  std::shared_ptr<T> returnValue;
133  while ( ! ( returnValue = tryToGet()) ) {
134  add( std::unique_ptr<T>(iMakeFunc()) );
135  }
136  iClearFunc(returnValue.get());
137  return returnValue;
138  }
139 
140  private:
141  void addBack(T* iItem){
142  m_availableQueue.push(iItem);
144  }
145 
146  tbb::concurrent_queue<T*> m_availableQueue;
147  std::atomic<size_t> m_outstandingObjects;
148  };
149 
150 }
151 
152 
153 
154 #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:510