Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Creating an atomic function

void foo ( Bar* bar , void(Bar::*qux)(void) )
{
    if ( bar )
    {
        bar->qux();
    }
}

The problem is:

  1. bar can be deleted after the check by another thread.

  2. 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.

like image 967
Kolyunya Avatar asked Sep 13 '12 13:09

Kolyunya


People also ask

What is an atomic function in C?

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.

Is ++ an atomic operation in C?

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.

What is meant by atomic function?

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.

What is atomic data type in C?

There are four primitive atomic data types: booleans, integers, characters and floats.


2 Answers

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.

like image 90
Maxim Egorushkin Avatar answered Sep 19 '22 08:09

Maxim Egorushkin


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.

like image 21
Mike Seymour Avatar answered Sep 19 '22 08:09

Mike Seymour