c++ - Safely release a resource on a different thread -


i have class similiar to:

class a{     private:     boost::shared_ptr< foo > m_pfoo; } 

instances of destroyed on gui thread may hold last reference foo. destructor foo potentially long running, causing undesirable pause on gui thread. foo destroyed on separate thread in case, foo's self contained , not critical released immediately.

currently, use pattern this:

a::~a(){     auto pmtx = boost::make_shared<boost::mutex>();     boost::unique_lock<boost::mutex> destroyergate(*pmtx);     auto pfoo = m_pfoo;     auto destroyer = [pmtx,pfoo](){         boost::unique_lock<boost::mutex> gate(*pmtx);     };      m_pfoo.reset();     pfoo.reset();     s_cleanupthread->post(destroyer); } 

essentially, capture in lambda , lock until released object. there better way accomplish this? seems more complicated needs be.

a should not responsible destruction of target of m_pfoo. destruction of resource shared_ptr points responsibility of shared_ptr, in mind shouldn't micro-managing thread on destruction of real object occurs inside ~a.

instead of implementing new type of smart pointer suits needs, think compromise here take logic related deletion of underlying object out of ~a , move custom deleter provide shared_ptr upon construction. if happy current deallocation strategy, think satisfactory approach. agree others might want investigate strategies don't involve creating new thread every deallocation.

you can find docs on how provide deleter smart_ptr here. scroll down 'constructors taking deleter' (also might want documentation specific version of boost using).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -