[Interest] QSqlDatabase and Multithreading

Philipp Kursawe phil.kursawe at gmail.com
Wed Jan 22 16:39:24 CET 2014


Your database class uses a std::recursive_mutex (not the Qt mutex, its a
resource waster!) to synchronize access to the database.
Then in the method that returns a new shared pointer of QSqlDatabase you
use a std::lock_guard with that mutex to allow only one thread to use the
DB. I usually also assert that the calling thread is not the UI thread.
So when you create 4 threads they can all access the DB and dont have to
worry at all. When they get the DB back from your method, they are the
exclusive user. Of course you could further define read-access from any
thread while another has exclusive rights. But you could run into table
locks, which is a problem of SQLite only, iirc.


On Wed, Jan 22, 2014 at 4:18 PM, Soroush Rabiei <soroush.rabiei at gmail.com>wrote:

> Hi
>
> I'm writing a data-intensive application which must wait for large chunks
> of data from a remote database, sometimes about 10 seconds. So I want to
> keep UI in main thread (which one is running event loop) and move all data
> operations to other threads. I can see how to connect signals/slots from UI
> to waiter/worker threads, though I can't find an elegant way to properly
> change my data classes.
>
> I'm using a singleton-pattern class, Database, which holds QSqlDatabase.
> Everybody else should use this class to pass queries, see if database is
> still connected, and other tasks. The problem is that:
>
> A connection can only be used from within the thread that created it.
> Moving connections between threads or creating queries from a different
> thread is not supported.
> My question is how can I make connections between UI and second thread?
> All I can think of is to derive Database class from QThread. But then, what
> would run() be? And then other data processor classes (which all do some
> queries from db) should be derived from QObject and moved to the only
> instance of Database class? That violates the rule: Don't mix moveToThread
> and derivation ways.
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/interest
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20140122/b2a9a00d/attachment.html>


More information about the Interest mailing list