Em qui 15 maio 2014, às 00:38:46, Markus Pointner escreveu: > Hi, > > I'd like to use a QAtomicInt to generate IDs, by calling > fetchAndAddOrdered(1) to get a new ID. Sooner or later the QAtomicInt will > reach INT_MAX (or whatever the constant is). Is it ok to continue with > fetchAndAddOrdered(1), or do I have to manually reset the value to a sane > minimum?
On all currently-supported platforms, it will wrap around to INT_MIN and start generating negative numbers from there until -1, and then go to zero. Since fetchAndAddOrdered is opaque to the compiler on most current implementations, the undefined behaviour of signed integers overflow does not really apply. We've used that technique for Qt internal counters for some time. Examples: http://code.woboq.org/qt5/qtbase/src/corelib/plugin/quuid.cpp.html#966 http://code.woboq.org/qt5/qtbase/src/gui/image/qicon.cpp.html#_ZN12QIconPrivateC1Ev http://code.woboq.org/qt5/qtbase/src/gui/image/qimage.cpp.html#_ZN10QImageDataC1Ev http://code.woboq.org/qt5/qtbase/src/gui/opengl/qopengltextureglyphcache.cpp.html#60 http://code.woboq.org/qt5/qtbase/src/network/kernel/qhostinfo.cpp.html#164 We used to use that for timer IDs too, until someone ran into problems with the overflow to negative numbers. See http://blog.qt.digia.com/blog/2008/10/22/a-never-ending-struggle/. After that, we switched the timer IDs to a lock-free free list. > I am aware that for regular non-atomic ints, this would be undefined > behaviour, whereas unsigned ints are defined to wrap around. I would prefer > the wrap-around behaviour for my atomic value. Then use QAtomicInteger<unsigned>. That is guaranteed to exist and work on all platforms. If you need a larger address space, use QAtomicInteger<quintptr> or check if Q_ATOMIC_INT64_IS_SUPPORTED is defined. http://doc-snapshot.qt-project.org/qt5-stable/qatomicinteger.html#details Also, with Qt 5.3, you can simply do: int id = ++atomic; as we brought back the convenience API from Qt 4 and expanded it. http://doc-snapshot.qt-project.org/qt5-stable/qatomicinteger.html#operator-2b-2b -- Thiago Macieira - thiago.macieira (AT) intel.com Software Architect - Intel Open Source Technology Center _______________________________________________ Interest mailing list Interest@qt-project.org http://lists.qt-project.org/mailman/listinfo/interest