Important: Please read the Qt Code of Conduct -

Qthread and containers

  • I have 2 thread and 1 qlist.
    First thread insert the objects in the qlist.
    The second thread remove the objects.
    I use QMutex and QWaitCondition for write access but I wonder: is safe ask with count(), without blocking, how many objects are in qlist?
    Thank ...

  • Lifetime Qt Champion


    What do you mean by safe ?
    The result might not be accurate but technically you are not modifying the container.

  • Moderators

    is safe ask with count(), without blocking, how many objects are in qlist?

    To add to what @SGaist said - don't do it. count() does arithmetic (basically something like end - begin) and if those are being written on another thread you will get garbage result, possibly negative numbers or something a lot larger than actual count.

  • Thank you for yours time,
    what I would know is:
    is count() function an 'atomic operation'?
    The function count return a int value, 32 bit size (the size (o half size) of a microcontroller register ).
    if the container's elements number change, I suppose but I'm not sure, the return value can vary from +1 or -1 from previous value.

  • Moderators

    is count() function an 'atomic operation'?

    No, it's not. The definition for it is:

    inline int count() const { return p.size(); }

    and p.size() is:

    inline int size() const Q_DECL_NOTHROW { return d->end - d->begin; }

    where begin and end are indices into an internal buffer.
    So, like I said, it does arithmetic (apart from bunch of indirections, which are definitely not atomic). It can so happen that some operation updates begin and end by shifting them. If your other thread happens to call count() before both values are written begin can happen to be larger than end and count() would result in a negative number. It's not just +/-1. It can be any number, as list elements can be added/removed in bulk.

  • thank you, very well, very exhaustive !!!

Log in to reply