void foo ( Bar* bar , void(Bar::*qux)(void) )
{
if ( bar )
{
bar->qux();
}
}
The problem is:
bar
can be deleted after the check by another thread.
I can not add a mutex member to Bar
in order to lock it.
Thus I wonder, if I can tell the processor to run this function atomically, and how would I do so? I've spent way to much time on Google, but found no understandable manuals...
P.S. Debian, gcc , Boost NOT allowed, C++11 IS allowed.
Atomic operations are intended to allow access to shared data without extra protection (mutex, rwlock, …). This may improve: ● single thread performance ● scalability ● overall system performance.
On objects without an atomic type, standard never defines ++ as an atomic operation. C11 defines atomic types in stdatomic. h. If you have an object with an atomic type, a postfix and prefix operators ++ will define an atomic operation as: read-modify-write operation with memory_order_seq_cst memory order semantics.
Atomic functions are perceived to be a fancy feature on top which allows for the implementation of platform-independent applications in a lock-free manner. The latter, however, is actually the fundamental contribution since atomic operations may exhibit a vastly different behavior on distinct hardware architectures.
There are four primitive atomic data types: booleans, integers, characters and floats.
You probably want to use a smart pointer with shared ownership semantics (e.g. shared_ptr
, intrusive_ptr
) to make sure the object stays alive as long as you refer to it.
You want to temporarily share ownership of the object, in order to prevent another thread from deleting it. This is a job for shared_ptr
, using weak_ptr
to allow deletion when we don't need to access it:
void foo ( std::weak_ptr<Bar> weak_bar , void(Bar::*qux)(void) )
{
if (std::shared_ptr<Bar> bar = weak_bar.lock())
{
// We now share ownership of the object - it won't be deleted
bar->qux();
}
// We have released ownership - it can now be deleted
}
Of course, you still need synchronisation if multiple threads need to access the object; this only solves the problem of deletion specified in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With