Accessing the same Database from different threads

  • Hi guys,

    I know there is a lot about this problem but after searching on the net I didn't found an exhaustive answer.

    I have the main thread that has its own connection to the database and works well. Now I have to create a second thread that needs the access to the same database.

    if I understood well, if I create two different connections with two different names that point to the same database there won't be any problems.

    I'm using SQLite database and as default the libraries compiled by QT should have SQLITE_THREADSAFE=1 setting the threading mode to Serialized allowing multithread operations.

    what I didn't understand is what happens in the case where both the threads are trying to access at the same moment the same database (using two different connections)?


    //main thread

    void thread1{
    QSqlQuery qry(db);

    qry.prepare("UPDATE Time SET Hour = 10, Min = 20 , Sec = 30");


    void thread2{
    QSqlQuery qry(db_2);

    qry.prepare("SELECT rowid FROM Time WHERE Hour = 10 AND Min = 20 AND Sec = 30");


    Are they both executed one after the other? If the answer is yes, I suppose that it's not possible to know wich one is executed first.

    Thank you for your time.

  • Lifetime Qt Champion


    No, it's not possible, the order of the execution of the threads is unknown.

  • @SGaist
    Thank you for your answer!