Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Evaluating QSqlQuery accross different threads
Mike Neuhaus last edited by Mike Neuhaus
My application uses the QtSqlite driver to interact with a database. The QT docs states that no database connection can be moved between threads. Because of this limitation I created a serializer to execute all the queries from a single thread. Then I notify other threads via the signal/slot system (or call a blocking function that waits until the scheduled query is executed succesfully) once the query is done. The serializer creates a local QSqlQuery object that is used to execute the query string. Once the execution is done I copy the QSqlQuery object to the designated thread which (and destroy the local copy before any other thread is able to access the copied QSqlQuery object) scheduled it, basically moving the executed QSqlQuery object to another thread you might say. However I have some memory leak issues, when the QSqlQuery object (the one that is copied from the serializer thread to its own thread) is destroyed the resources are not free'd. I checked the internal reference counter to see how many references there are when the particular query is destroyed and I can confirm this is a value of '1' when the QSqlQuery is being destroyed. I'm not sure why this could be a problem as the query is created in the same thread where I created my database connection. I'll hope someone can shed some light on this subject.
@Mike-Neuhaus Somehow this sounds complicated. Why should all these threads deal with QSqlQuery? Why don't you let one thread access the database and provide data (not QSqlQuery!) to all the other threads?
Mike Neuhaus last edited by
@jsulm This is indeed a solution, I could cache the results and give the other threads access to the cached results. However the serializer is an integration in an existing system, the current software is using QSqlQuery extensively that's the only reason why I want to remain using the QSqlQuery class.
I suspect you'll need to delve into the internal details of QSqlQuery to figure out if what you're doing is possible. Subscribe to the Interest mailing list (http://lists.qt-project.org/mailman/listinfo/interest ) and ask there -- Qt engineers are active there.
What you want depends heavily on the driver in use, whether or not the SQLite driver can be used from different threads, I can't say. But the problem isn't with the SQL query class itself, it's with the driver (and the
QSqlDatabasethat holds a reference to the driver).
Mike Neuhaus last edited by
Thanks for all the answers, I ended up posting it on the interest. For now I implemented the cached results solution.