Waiting for data in QQueue
-
Hi everyone !
I want to wait on a QQueue to have data to treat and see if I get what I expect.
For the waiting part, I tought about using a QtConcurrent::run, calling a function where I could do a while loop to check data in my queue. Also, I saw some code on StackOverflow wich inspired me this :// /* Wait for reception */ bool timeout = false; _timeout = 100; queueAckEmpty = queueAck.isEmpty(); while (!timeout && queueAckEmpty){ qCritical() << "Ack empty : " << queueAckEmpty; queueAckEmpty = queueAck.isEmpty(); timeout = elapsedTime.elapsed() > _timeout; QApplication::processEvents(QEventLoop::AllEvents); }
The problem with my code is that I would expect it to go out of the while loop as soon I have data in the queue but I don't and it print hundreds "Ack empty : ".
I wanted to have your opinion on which is the best way to do this and why ?
Thanks :)
-
@Clarck_D
If you are going to do it this way (you would be better with signal & slot), oneprocessEvents()
in a loop without delay is awfully busy. You would want some delay in the loop, like 1/100th or 1/1000th of a second to avoid too many calls. -
If you write a little wrapper class around QQueue, you could use synchronization classes like QMutex:
- Your queue offers a mutex
- The mutex is locked while the queue is empty
- The code processing the items of your queue wait for the mutex to unlock
- When an item is added to the queue, the mutex is unlocked. As the last item is removed from the queue, the mutex is locked again.
-
I think I'm gonna try to use QtConcurrent and QMutex then. Thanks guys :)
-
Hi,
Looks like a case for QWaitCondition.
-
You would use QtConcurrent once you have have data in your queue.
-
-
@SGaist No I can't because I want to use it for waiting data
I came across this :
However, QtConcurrent can't be used when communication with the running thread is needed, and it shouldn't be used to handle blocking operations.
So I guess that get rid of Qtconcurrent for my purpose.
For now I went with the code I posted.Still, thanks guys ;)
-
There is mainly two use cases for multithreading:
- Avoid blocking some other operation (often GUI)
- Distribute work across multiple cores
QtConcurrent is good for 2) (especially if you need to perform an operation across multiple items in a container), but not really suited for 1)