implement thread for consuming operations in Qt
I have never worked with QThread in Qt, or with threads in general, so the topic is more then new to me. Still I have to use QThread's in order to avoid the blocking of my main application due to some heavy computations.
So I want to put my heavy computations in a thread and if they take too much time I want to kill the thread (which was also suggested to me).
I have the following declaration for my thread:
class myopThread : public QThread
{
public:
void run();
};
void myopThread::run()
{
std::cout<<"here in the thread. Are you working?"<<endl;
//include all the consuming operations here
exec();
}
I also start the thread in my main application:
myopThread *t=new myopThread;
t->start();
It seems to 开发者_JAVA技巧work. Still now I would want to kill this thread whenever the computing time of the operations in run() is greater then 2 minutes let's say.
I do not know how to implement this. Any help is more then welcomed.
Thank you in advance, madalina
In narrow point of view you question can be implemented with watchdog pattern, who periodically checks if thread shutdown time has been fired. But this way grants many errors and spend of time. Review possibility to use QThreadPool - forgot about own management of thread allocation/destroying
One more benefit of pool is improving long operation of thread creation. Instead of wait new thread just reuse existing one.
Try using a timer:
myopThread *t = new myopThread;
QTimer::singleShot(120000, myopThread, SLOT(terminate()));
t->start();
Qt's doc:
void QThread::terminate () [slot]
Warning: This function is dangerous and its use is discouraged. The thread can be terminate at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to cleanup after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.
A better solution is to create a own slot terminateAsSoonAsPossible()
in your thread which sets a variable shouldTerminate
to true which you can poll in your thread and exit if it's true.
"Bob's the programmer has a programming problem. Bob decided to use threads. Now Bob has two problems." --From a thread on StackOverflow
May I suggest that you take a look at processEvents(), which will help your program stay responsive to the OS very simply and without threads or timers? I had a similar choice to make and found this was a good choice. It may or may not be the best for your project.
processEvents reference
精彩评论