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 ... -
Hi,
What do you mean by safe ?
The result might not be accurate but technically you are not modifying the container. -
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 likeend - 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.
Bye -
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
andend
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 updatesbegin
andend
by shifting them. If your other thread happens to callcount()
before both values are writtenbegin
can happen to be larger thanend
andcount()
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.