I'm working on a scenario where we want to asynchronously execute INSERT
/DELETE
statements on a database table (it's a fire-and-forget scenario). I'm planning to simply fire a signal with relevant data, and have the thread's event loop process each signal similar to the following example:
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
connect(signalSource, &SignalSource::dataReady, worker, &Worker::updateMyFancyTable);
workerThread.start();
The thread is supposed to have its own database connection opened as long as it is running. I would do it like this (with added error handling, of course):
connect(&workerThread, &QThread::started, worker, &Worker::establishDatabaseConnection);
When stopping the thread, it is supposed to finish its work and then close the database connection.
As far as I understand, calling quit() on the thread will first process all remaining signals (if any) and then exit the thread's event loop.
How do I properly close the database connection in a scenario like this?
- Do I emit a signal for closing the connection before calling
quit()
? - Do I close the connection in a slot in the main thread which gets called once
QThread::finished
has been emitted? - Something else?