Lock-free swap of two unique_ptr

后端 未结 3 1017
梦毁少年i
梦毁少年i 2021-01-30 16:20

Swapping two unique_ptrs is not guaranteed to be threadsafe.

std::unique_ptr a, b;
std::swap(a, b); // not threadsafe

Sin

3条回答
  •  余生分开走
    2021-01-30 17:01

    Is this a valid solution to the

    You'll have to write your own smart pointer

    template
    struct SmartAtomicPtr
    {
        SmartAtomicPtr( T* newT )
        {
            update( newT );
        }
        ~SmartAtomicPtr()
        {
            update(nullptr);
        }
        void update( T* newT, std::memory_order ord = memory_order_seq_cst ) 
        {
            delete atomicTptr.exchange( newT, ord );
        }
        std::shared_ptr get(std::memory_order ord = memory_order_seq_cst) 
        { 
            keepAlive.reset( atomicTptr.load(ord) );
            return keepAlive;
        }
    private:
        std::atomic atomicTptr{nullptr};
        std::shared_ptr keepAlive;
    };
    

    it's based on @Jonathan Wakely's snippet at the end.

    the hope is that things like this would be safe:

    /*audio thread*/ auto t = ptr->get() ); 
    /*GUI thread*/ ptr->update( new T() );
    /*audio thread*/ t->doSomething(); 
    

    the issue is that you could do something like this:

    /*audio thread*/ auto* t = ptr->get(); 
    /*GUI thread*/ ptr->update( new T() );
    /*audio thread*/ t->doSomething(); 
    

    and there's nothing to keep t alive on the audio thread when the GUI thread calls ptr->update(...)

提交回复
热议问题