Home>
About loading atomic indirect references

I searched, but it was difficult to find an article about this topic, so I asked a question. What I do not know is as follows.

Whether a pointer is inserted intostd :: atomicfor indirect reference, is it possible to access the contents of the pointer?
(18/08/30 12:17 postscript) Only the atomic variable of the pointer can access the reference destination.

Thanks for any help! :)

# include<iostream>
#include<atomic>
#include<thread>
struct mystruct
{
    ~ mystruct () {value = 0;}
    int value = 0;
};
class myclass
{
    mystruct m_mystruct;
    std :: atomic<mystruct *>m_atomic_mystruct_ptr;
public:
    myclass () {m_atomic_mystruct_ptr.store (&m_mystruct);}
    mystruct&get_mystruct () {return * m_atomic_mystruct_ptr.load ();}
    void mystruct_worker (std :: size_t num) {
        while (num->0)
            m_atomic_mystruct_ptr.load ()->value ++;
    }
};
int main ()
{
    myclass m;
    std :: thread t (&myclass :: mystruct_worker,&m, 10000);
    std :: this_thread :: sleep_for (std :: chrono :: nanoseconds (10));
    int i = m.get_mystruct (). value;// is this thread-safe?
    std :: cout<<i<<"\ n";
    t.joinable ()? t.join (): t.detach ();// (13:01 postscript) Simply t.join () is OK!
}
c++
  • Answer # 1

      

    Whether a pointer is inserted intostd :: atomicfor indirect reference, is it possible to access the contents of the pointer?

    No. The atomicity (thread safety) guaranteed bystd :: atomic<T *>pis only a write/read operation to the pointerpitself. The thread safety of theTtype object of the* ppointed to by the pointer must be handled by theTtype itself.

    The question posting code causes a data race inmy_struct :: value, so the program is undefined.


    It is not directly related to the subject matter, but I was interested in the place of the posting code. Sincethere is always joinable, it would be enough to writet.join ();. Also, ift.joinable ()is false,t.detach ()will throw an exceptionstd :: system_error(expected Is n’t it? "

    std :: thread t (&myclass :: mystruct_worker,&m, 10000);
    // ...
    ? T.joinable () t.join (): t.detach ();// ★

  • Answer # 2

    Hello.

    I have never thought of using it, but it is impossible.
    The atmic variable is wrapped in an atminc template and is gorgeous (not known in detail) so that it can be accessed atomically.
    When a pointer is an atmic variable, it is guaranteed to be atomically accessible as defined because the pointer itself is wrapped properly. However, the point is naturally unwrapped and naked. So there is no way to "go gnoyo", so it is not guaranteed that it can be accessed atomically.