[Interest] QAtomicInt overflow / wrap-around?

Thiago Macieira thiago.macieira at intel.com
Thu May 15 01:14:24 CEST 2014

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:

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.


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.


Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center

More information about the Interest mailing list