Swapping two unique_ptr
s is not guaranteed to be threadsafe.
std::unique_ptr a, b;
std::swap(a, b); // not threadsafe
Sin
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(...)