QList.size accross threads seg fault
-
Hi there,
I am trying to do the following:
I have 1 thread capturing packets and storing them 1 at a time in a QList.
I have a 2nd thread constantly looping while capturing checking if there are more packets to analyse, it uses QList.size() to check
The QList is shared between threads just by passing a pointer to each thread on creation.I have had several QList issues, out of range is a common one despite my loops getting a local copy of QList.size() before entering the loop.
I have now just seen (when debugging using qtcreator) that it failed at the line
@temp = (packets->size() - 1);@
It failed on that line despite executing several thousand times before... How is this even possible? I swear I must have gone fundamentally wrong somewhere in the design accross threads or something.Any help would be superb.
Cheers -
QList is "reentrant":http://qt-project.org/doc/qt-4.8/qlist.html so you have to use mutex for example to make operations on your QList thread-safe.
Here something about "reentrant and thread-safe":http://qt-project.org/doc/qt-4.8/threads-reentrancy.html#reentrant
Read too about QMutex and maybe QMutexLocker. -
Actually, I'd like to take one step back and suggest that instead of having a thread which loops all the time, what about you approach it "the Qt way" :) which means using signals and slots to cross those threads and you can use an event loop in both threads.
At minimum this means your thread that is now constantly looping will instead just do something when there is work to be done. This should free up one CPU. -
Why even use the QList? You could just pass the packets as the parameter of a signal from one thread to another. If there are a lot of packets and handling them takes some time you could even have a sort of middleman that would have a threadpool and that delegates the packets to available (free) threads.
-
Thanks for the replies, I don't believe slots and signals will cut it here, needs to be able to handle around 200k packets a second for large files (4GB +)
I need to store the packets somewhere so I can cycle back through them all repeatedly to do some processing. Every time packet X comes in I need to find packet Y and calculate latency between them
But I do realise now about QList and thread safety, relatively new to all this :)