May 10, 2012

GSDeveloper GSDeveloper
Lab Rat
4 posts

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.

3 replies

May 10, 2012

jobor jobor
Lab Rat
18 posts

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().

May 10, 2012

MuldeR MuldeR
Robot Herder
471 posts

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…

  1. int someFunction(/*other arguments*/, bool *abortFlag)
  2. {
  3.     while(workLeft && (*abortFlag != true))
  4.     {
  5.         /*do more work*/
  6.     }
  7. }

  1. bool abortFlag = false;
  2. extern QString someFunction(/*other arguments*/, bool *abortFlag);
  3. QByteArray bytearray = ...;
  4.  
  5. QFuture<QString> future = QtConcurrent::run(someFunction, bytearray, &abortFlag);

  1. abortFlag = true;
  2. QThreadPool::globalInstance()->waitForDone();

 Signature 

My OpenSource/Libre software at: http://muldersoft.com/ | Go visit the coop: http://youtu.be/Jay-fG9eaYk

May 23, 2012

GSDeveloper GSDeveloper
Lab Rat
4 posts

Ok. Thanks for your suggestions.

 
  ‹‹ update resize when changing button’s title      [SOLVED] How to configure c32.lib correctly? ››

You must log in to post a reply. Not a member yet? Register here!