Atomic reading with QAtomicInt / QAtomicPointer

How can I read the value of QAtomicInt or QAtomicPointer atomically in Qt4 on all supported architectures? I donโ€™t care about ordering the memory here, I just want to be sure that I will not read the partially old, partially new value if another thread changes the value at the same time.

In Qt4, these classes only have cast statements for int or T *. There seems to be a newer code ( http://qt.gitorious.org/qt/qtbase/blobs/master/src/corelib/thread/qbasicatomic.h ) that distinguishes between non-atomic load () and atomic loadAcquire (). Atomic C ++ 11 also has an atomic load () ( http://en.cppreference.com/w/cpp/atomic/atomic/load ). Therefore, I am concerned that the methods provided by Qt4 are not safe enough.

I know that fetchAndAddRelaxed (0) should work, but it looks like a hack and is probably not optimal in terms of performance.

+4
source share
1 answer

In principle, the answer is yes. Almost all modern platforms allow at least 32-bit or 64-bit atomic loads / storages, provided that the variables are aligned. (Atomic is used here in the sense that you will not load the "partial" value)

Now itโ€™s not clear in the Qt documentation that their atomization provides this using the base (what they call non-nuclear) load() and store() . 'loadAcquire ()' and especially `fetchAndAddRelaxed (0) 'cost more than you need -' loadAcquire 'is by far the cheapest of these 2.

If I were you, I would just use load () and store (). If you need an extra guarantee for Qt documentation, loadAcquire is the cheapest way, and in an architecture like x86, like load ().

The best way is to use the C ++ 11 atom with the laid-back memory model you need.

+3
source

Source: https://habr.com/ru/post/1440313/


All Articles