QSqlDatabase in multithreaded environment



  • Hi,

    I have a problem - well, it's more a question than a problem.

    I'm opening a QSqlDatabase connection in a thread, and am accessing it from multiple other threads (via QSqlQuery).

    Now, I know that (according to the documentation) this shouldn't be done ("or can't, in their words":http://qt-project.org/doc/qt-4.8/threads-modules.html#threads-and-the-sql-module)

    Our application has been running for quite some time without ever showing any issues. If properly locked, no two threads are accessing the connection at the same time and everything seems to be running smoothly (and yes, I can guarantee that multiple threads are trying to access the connection simultaneously).

    My question is:
    Is there a reason why the docs say a connection can't be used in threads other than the creator thread?

    I have several options to circumvent this and restrict DB access to the creator thread, but they're all rather time consuming and I'd like to avoid having to implement them if the threading issue could be resolved with simple locks.



  • Hi

    Your link only say it's not supported. I would guess that this implies that some databases could fail with e.g. dead lock or other problems... Another issue would be using the same connection in multiple threads without using QMutex.

    ..so it pretty much depends on your implementation if this will work, and perhaps the database itself.

    I have used multiple threads with SQL connection, but in my case - each thread opened their own connection and that worked for me :-)



  • I wrote some multi-threaded application in Qt using MySQL database before. There was no problem.

    Documentation says that the class is not thread-safe (does not implement move semantics, by the Qt way) I think there should not be any problem if you're using a DBMS like MySQL. because the DBMS can handle multiple users connected to a db in same time. You should only take care of logical order of operations in your program. For example, before creating a table by a thread, other thread should not query some data from it. or before opening connection to a db by a thread, any other thread should not try to interact with db.

    In the case you where ysing SQLite, your database is a normal file on the disk. So problems may occure.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.