#ifndef NCrystal_FactoryUtils_hh #define NCrystal_FactoryUtils_hh //////////////////////////////////////////////////////////////////////////////// // // // This file is part of NCrystal (see https://mctools.github.io/ncrystal/) // // // // Copyright 2015-2022 NCrystal developers // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // // //////////////////////////////////////////////////////////////////////////////// #include "NCrystal/NCDefs.hh" #include "NCrystal/NCSmallVector.hh" #include #include #ifndef NCRYSTAL_DISABLE_THREADS # include #endif namespace NCrystal { constexpr unsigned CachedFactory_KeepAllStrongRefs = std::numeric_limits::max(); template struct CFB_Unthinned_t { //Default key thinning strategy is to not actually do any thinning. If //implementing a cache which uses thinning, the Optional& //arguments can be used as a place to cache the thinned key (to avoid //thinning again and again). using key_type = TKey; using thinned_key_type = TKey; template static typename TMap::mapped_type& cacheMapLookup( TMap& map, const key_type& key, Optional& ) { return map[key]; } }; template< class TKey, class TValue, unsigned NStrongRefsKept = 5, class TKeyThinner = CFB_Unthinned_t> class CachedFactoryBase { public: ///////////////////////////////////////////////////////////////////////////////// // // Base class for multi-thread safe factories. Client code must implement // the actualCreate function, plus a few cosmetic functions. Factories will // always keep weak references (weak_ptr) to the created objects, but can be // configured with the NStrongRefsKept parameter to also keep strong // references (shared_ptr) to them (thus ensuring the created objects are // kept alive and won't have to be recreated later). Strong refs are kept to // the last NStrongRefsKept objects accessed. // // The strong refs and any dangling weak refs can be cleaned up by an explicit // call to the cleanup function of a particular factory, or simply by calling the // global clearCaches function which will in turn call the cleanup function of // all factories. // ///////////////////////////////////////////////////////////////////////////////// using key_type = TKey; using thinned_key_type = typename TKeyThinner::thinned_key_type; typedef TValue value_type; typedef std::shared_ptr ShPtr; typedef std::weak_ptr WeakPtr; ShPtr create(const key_type&); ShPtr createWithoutCache(const key_type&) const; virtual std::string keyToString( const key_type& ) const = 0; virtual const char* factoryName() const = 0; //Cleanup cache, release all kept strong and weak references (this function //automatically registered with and invoked by global clearCaches //function). But note that it is NOT called from the factory destructor, //since that can trigger memory errors during programme shutdown.: void cleanup(); //To automatically call a function whenever cleanup() is invoked: void registerCleanupCallback(std::function); struct Stats { std::size_t nstrongrefs, nweakrefs; }; Stats currentStats(); //NB: This might seem sensible, but gives troubles since most //CacheFactoryBase instances are kept as global static objects, with //undefined destruction order: ~CachedFactoryBase() { cleanup(); } protected: virtual ShPtr actualCreate(const key_type&) const = 0; private: struct CacheEntry { bool underConstruction = false; bool wasInvalidatedDuringConstruction = false; WeakPtr weakPtr; void clear() { underConstruction = wasInvalidatedDuringConstruction = false; weakPtr.reset(); } }; using CacheMap = std::map; CacheMap m_cache; std::mutex m_mutex; class StrongRefKeeper; StrongRefKeeper m_strongRefs; bool m_cleanupNeedsRegistry = true; SmallVector,1,SVMode::LOWFOOTPRINT> m_cleanupCallbacks; }; /////////////////////////////////////////////////////////////////////////// // Global control affecting all CachedFactoryBase instances (the default // // settings of these can also be controlled by environment variables). // /////////////////////////////////////////////////////////////////////////// void enableFactoryVerbosity( bool status = true ); bool getFactoryVerbosity(); } //////////////////////////// // Inline implementations // //////////////////////////// namespace NCrystal { namespace thread_details { #ifndef NCRYSTAL_DISABLE_THREADS inline std::thread::id currentThreadIDForPrint() { return std::this_thread::get_id(); } #else inline constexpr const char * currentThreadIDForPrint() noexcept { return ""; } #endif } namespace detail { #ifndef NCRYSTAL_DISABLE_THREADS void registerThreadWork(std::thread::id); void registerThreadWorkDone(std::thread::id); void registerThreadAsWaiting(std::thread::id); void registerThreadAsFinishedWaiting(std::thread::id); #endif } template class CachedFactoryBase::StrongRefKeeper { std::vector m_v; void reserveCapacity( std::vector& v ) { if (NStrongRefsKept>0) v.reserve(NStrongRefsKept > 512 ? 512 : NStrongRefsKept); } public: StrongRefKeeper() { reserveCapacity(m_v); } void clear() { m_v.clear(); } bool empty() const { return m_v.empty(); } std::size_t size() const { return static_cast(m_v.size()); } void wasAccessedAndIsNotInList( const ShPtr& sp ) { //was just created, so we know it is not already in the list. if (NStrongRefsKept==0) return; if (NStrongRefsKept==CachedFactory_KeepAllStrongRefs) { m_v.push_back( sp ); return; } if ( m_v.size()==NStrongRefsKept ) { //make room, discard first entry (was accessed longest ago). for ( auto i : ncrange(typename decltype(m_v)::size_type(1),m_v.size() ) ) m_v[i-1] = std::move(m_v[i]); m_v.pop_back(); } m_v.push_back( sp ); } void wasAccessed( const ShPtr& sp ) { //was accessed, might (or might not) already be in the list. //NStrongRefsKept==CachedFactory_KeepAllStrongRefs if (NStrongRefsKept==0) return; //Check if we already have it: auto it = m_v.begin(); auto itE = m_v.end(); for (;it!=itE;++it) { if ( *it == sp ) { //Already there! Shuffle it to the end: if ( std::next(it) == itE ) return;//already at end auto itLast = std::prev(itE); for ( ;it!=itLast; ++it) *it = std::move(*std::next(it)); *itLast = sp; return; } } //was not already in the list: wasAccessedAndIsNotInList(sp); } void releaseOne( const ShPtr& sp ) { if ( !sp || empty() ) return; auto itE = m_v.end(); auto it = std::find( m_v.begin(), itE, sp ); if ( it == itE ) return;//not there //Move it to the end and pop_back: auto itLast = std::prev(itE); for ( ;it!=itLast; ++it) *it = std::move(*std::next(it)); m_v.pop_back(); } void releaseMany( const std::set& to_remove ) { if ( to_remove.size() <= 1 ) { releaseOne( *to_remove.begin() ); return; } decltype(m_v) new_v; reserveCapacity(new_v); for ( auto& sp : m_v ) { if ( !to_remove.count(sp) ) new_v.push_back( std::move(sp) ); } std::swap(new_v,m_v); } }; template inline void CachedFactoryBase::registerCleanupCallback(std::function fn) { NCRYSTAL_LOCK_GUARD(m_mutex); m_cleanupCallbacks.push_back(fn); } template inline void CachedFactoryBase::cleanup() { NCRYSTAL_LOCK_GUARD(m_mutex); m_strongRefs.clear(); auto it = m_cache.begin(); auto itE = m_cache.end(); while (it!=itE) { auto itNext = std::next(it); if ( it->second.underConstruction ) { it->second.wasInvalidatedDuringConstruction = true; } else { m_cache.erase(it); } it = itNext; } for ( const auto& fn : m_cleanupCallbacks ) fn(); } template inline typename CachedFactoryBase::Stats CachedFactoryBase::currentStats() { NCRYSTAL_LOCK_GUARD(m_mutex); Stats s; s.nstrongrefs = m_strongRefs.size(); s.nweakrefs = static_cast(m_cache.size()); return s; } template inline std::shared_ptr CachedFactoryBase::createWithoutCache( const TKey& key ) const { if ( getFactoryVerbosity() ) std::cout<< this->factoryName() <<" (thread_"< inline std::shared_ptr CachedFactoryBase::create(const TKey& key) { /////////////////////////////////////////////////////////////////////////////////////////////////////// class Guard { //Local guard class. Kind of like std::lock_guard, but can remove set //underConstruction flag as well. std::mutex& m_mutex; bool* m_constructFlag = nullptr; bool m_isLocked = false; public: #ifdef NCRYSTAL_DEBUG_LOCKS # define NCRYSTAL_DEBUG_LOCKS_ARGS __FILE__,__LINE__ #else # define NCRYSTAL_DEBUG_LOCKS_ARGS #endif constexpr bool isLocked() const noexcept { return m_isLocked; } bool weHoldConstructFlag() const { return m_constructFlag != nullptr; } Guard( std::mutex& mutex ) : m_mutex(mutex) {} void releaseConstructFlagWithoutSetting() { m_constructFlag = nullptr; } void setConstructFlagFalseAndRelease() { if ( m_constructFlag != nullptr ) { ensureLock(NCRYSTAL_DEBUG_LOCKS_ARGS); *m_constructFlag = false; m_constructFlag = nullptr; } } void setConstructFlagWithGuard( bool* constructFlag ) { nc_assert(constructFlag); ensureLock(NCRYSTAL_DEBUG_LOCKS_ARGS); m_constructFlag = constructFlag; *m_constructFlag = true; } ~Guard() { setConstructFlagFalseAndRelease(); ensureUnlock(NCRYSTAL_DEBUG_LOCKS_ARGS); } #ifdef NCRYSTAL_DEBUG_LOCKS void ensureLock(const char* file,unsigned lineno) #else void ensureLock() #endif { if (!m_isLocked) { #ifdef NCRYSTAL_DEBUG_LOCKS std::cout<<"NCrystal::FactoryUtils:: About to lock mutex due to Guard::ensureLock() from "< fct_cleanup = [this](){ this->cleanup(); }; registerCacheCleanupFunction(fct_cleanup); } if ( verbose ) std::cout<< this->factoryName() <<" (thread_"< thinned_key; auto& cache_entry = TKT::cacheMapLookup( m_cache, key, thinned_key ); ShPtr res = cache_entry.weakPtr.lock(); if (!!res) { if ( verbose ) std::cout<< this->factoryName() <<" (thread_"<factoryName() <<" (thread_"<factoryName() <<" (thread_"<create(key); } else { //all ok, populate cache:: if ( verbose ) std::cout<< this->factoryName() <<" (thread_"<factoryName() <<" (thread_"<factoryName() <<" (thread_"<create(key); } guard.ensureUnlock(NCRYSTAL_DEBUG_LOCKS_ARGS); } } } } #endif