Hi,
Use a QMutex to prevent the concurrent access to the list.
Hi,
Use a QMutex to prevent the concurrent access to the list.
Òscar Llarch i Galán
QList won't do without a mutex. You need a lock-free queue, but that only works as long as all you do is atomically push and pop elements. You are pretty much doomed if your UI thread can inspect the whole structure; for instance, imagine that it is inspecting an element and suddenly the DataToDisc thread pops and deletes that element...
Vikram.Saralaya (8th January 2016)
Thanks yeye.. But how can I atomically push and pop elements?
I think yeye_olive is trying to tell you that you can't push and pop atomically using a QList - in a multithreaded app, you need to protect access using a mutex if you want to ensure a writer doesn't corrupt what a reader is looking at.
Indeed, general-purpose containers such as QList do not atomic push and pop operations. If you want to avoid synchronization with mutexes as much as possible, you need specialized containers; see, for instance, the Boot.Lockfree library.
However, the fact that the UI thread can inspect the whole container means that you will probably need heavy synchronization.
Thanks Yeye and d_stranz. Its good to know that its not trivial to atomically push and pop in any of the available qt containers.
Mutex isn't an option to me since it does add a lag to the UI thread.
For anyone interested in how I dealt with this:
I ended up creating a custom circular buffer with QAtomicInteger write pointer. I preallocate memory so my DataToDisc thread now just acts like a reader (without worrying about the growing list). Readers can never read beyond the write pointer and hence no corrupt data will ever be read. Works well!
Regards
Vikram
Bookmarks