Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:28:21

0001 #ifndef RecoTracker_MkFitCore_src_Pool_h
0002 #define RecoTracker_MkFitCore_src_Pool_h
0003 
0004 #include "Matriplex/Memory.h"
0005 #include "oneapi/tbb/concurrent_queue.h"
0006 
0007 namespace mkfit {
0008 
0009   /**
0010    * Pool for helper objects. All functions are thread safe.
0011    */
0012   template <typename TT>
0013   class Pool {
0014   public:
0015     Pool() = default;
0016 
0017     ~Pool() { clear(); }
0018 
0019     void clear() {
0020       TT *x = nullptr;
0021       while (m_stack.try_pop(x)) {
0022         destroy(x);
0023       }
0024     }
0025 
0026     size_t size() const { return m_stack.unsafe_size(); }
0027 
0028     void populate(int threads = Config::numThreadsFinder) {
0029       for (int i = 0; i < threads; ++i) {
0030         m_stack.push(create());
0031       }
0032     }
0033 
0034     auto makeOrGet() {
0035       TT *x = nullptr;
0036       if (not m_stack.try_pop(x)) {
0037         x = create();
0038       }
0039       auto deleter = [this](TT *ptr) { this->addBack(ptr); };
0040       return std::unique_ptr<TT, decltype(deleter)>(x, std::move(deleter));
0041     }
0042 
0043   private:
0044     TT *create() { return new (Matriplex::aligned_alloc64(sizeof(TT))) TT; };
0045 
0046     void destroy(TT *x) {
0047       x->~TT();
0048       std::free(x);
0049     };
0050 
0051     void addBack(TT *x) { m_stack.push(x); }
0052 
0053     tbb::concurrent_queue<TT *> m_stack;
0054   };
0055 
0056 }  // end namespace mkfit
0057 #endif