Please nominate your Qt Champions for 2021! https://forum.qt.io/topic/132134/looking-for-the-2021-qt-champions
QList concurrent access and modification done right?
I have a class with QList in it, which is integrated every 100ms and some of the elements are processed based on time parameter. After the element has been processed it is removed from the list. Now at any one moment I also need to be able to insert new elements to that list. All this is done in one thread, so we are not talking about cross thread access.
The problem is also that I can't use QMutex and lock the list during the loop or the insertion/removal because some of the elements during their processing can also need to access the list and insert a new element.
Is this even possible?
Leonardo last edited by
I don't see a problem there. If you're using only one thread, there's no need for QMutex or worrying about concurrency.
A mutex is only needed when two different threads need to access the same variable. Since you only have one thread, you don't need to lock your list.
I'm not sure what you mean by "concurrent access" if you only have 1 thread... could you explain in more detail?
The list is in a class. That classed is used in one thread. The GUI thread sends "signals" to the working thread, thus inserting new processes to the list. But at the same time, in the working thread a loop is running based on QTimer (when the timer expires it sends a signal to the slot which runs one circle at the end of which the timer is set again, so we have a loop). So in that sequence the list can be accessed randomly from the loop function and the slot for insertion, right?
So in that sequence the list can be accessed randomly from the loop function and the slot for insertion, right?
Within one thread, only one slot can run at a time. Suppose your worker thread is in the middle of running the timer-expiry slot. If a signal arrives from the GUI thread, at this time, the signal's data will be put into a queue. The thread will wait for your timer-expiry slot to finish first, then it will start running your signal-from-GUI slot.
You don't need to lock your list with a mutex.
Thanks a lot for the reply :)