Kill QThreadPool
-
Hello Users,
I’m new in this forum and I have few questions using QtConcurrent :: run.
Basically I'm trying to test how a program can be robust, using more thread with "QtConcurrent::run", to write to a database in a non-blocking way.
It works perfectly in my procedure using "QtConcurrent::run" and connecting to a SQL Express Database with ODBC. To test I put a "Sleep" into my procedure (to simulate a "Long-Run" query) but when I close the program all my objects are destroyed except the thread created by "QtConcurrent::run". So the program then gets stuck and does not end immediately because of "Sleep". I discovered, in QT Help, that "Qtconcurrent" makes use of "QThreadPool", but I have not found anything that can stop instantly this thread. Do you have any suggestion about it?Thanks a lot
Giulio. -
You should cancel the long operation in the thread in a safe way instead of trying to kill the thread.
You can wait for the termination of the threads in the thread pool with QThreadPool::waitForDone(). -
You could create some global "abort" flag and pass a pointer to that flag into each function you call via QtConcurrent::run(). Inside the function you check the value of the flag (by using the pointer) and, if the flag has been set, return as soon as possible. When your application is about to exit, just set the flag...
@int someFunction(/other arguments/, bool *abortFlag)
{
while(workLeft && (*abortFlag != true))
{
/do more work/
}
}@
@bool abortFlag = false;
extern QString someFunction(/other arguments/, bool *abortFlag);
QByteArray bytearray = ...;QFuture<QString> future = QtConcurrent::run(someFunction, bytearray, &abortFlag);@
@abortFlag = true;
QThreadPool::globalInstance()->waitForDone();@ -
Ok. Thanks for your suggestions.