Question

How to synchronize access to data accessed from multiple threads in Qt model/view setup?

I'm using QTableView with a Model class.

Model extends QAbstractTableModel and has an instance of a custom class Net that holds actual data to be displayed to QTableView through data() call (accessed by Model::data())

My class listens on network data and runs on separate thread from which it updates it's data (simple fixed size array of 10 strings).

Data in my class has to be accessed both by a thread that constantly updates it and from Qt GUI by calling data() on Model.

I would assume I need to use mutex to synchronize access to my array of strings but QAbstractTableModel::data() is a const method so I can't lock boost::mutex in it.

What is a general pattern for synchronizing access to data in class that extends QAbstractTableModel and provides data to QTableView?

Was it helpful?

Solution

I don't think Qt's item-view classes (like QAbstractTableModel) and multiple threads will go together very well. The problem is that the QAbstractTableModel class is expected to notify all of the associated view classes every time the data changes, and also the view classes expect to be able to read data from the data-model at any time. Implementing that would be difficult to do (efficiently, anyway) if the updates and data are owned by a different thread. I suspect any multithreaded solution you came up with would need to be serialized so heavily that only one of the two threads would end up running at a time anyway, at which point you've effectively gone back to a single-threaded program, just with a very convoluted design :)

My suggestion would be to move your 10-string database into the main/Qt thread instead, if possible. Your networking operations can be moved into the main thread as well (use QSocketNotifier objects and make sure the I/O is all non-blocking, so that it can't hold off the Qt event loop and damage GUI performance); or you could keep the networking in a separate network thread and just have the network-thread send update-messages to the main/Qt thread telling the main/Qt thread how to update the database/table-model. The key is to have all reads and writes to the data model's database done by the main/Qt thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top