mardi 29 septembre 2015

Safely release a resource on a different thread

I have a class similiar to:

class A{
    public:
    boost::shared_ptr< Foo > m_pFoo;
}

Instances of A are destroyed on the GUI thread where they hold the last reference to a Foo. The destructor for Foo is potentially long running, causing an undesirable pause on my GUI thread. I would like for Foo to be destroyed on a separate thread, Foo's are self contained and it is not critical they get released immediately.

Currently, I use a pattern like 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();
    boost::thread destroyThread(destroyer);
}

Essentially, capture it in a lambda and lock until released from the object. Is there a better way to accomplish this?

Aucun commentaire:

Enregistrer un commentaire