views:

227

answers:

3

Hello,

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 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

+1  A: 

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.

Dewfy
+1  A: 

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.

Georg
terminate() on any thread in any langugage should be avoided like the plauge. Polling a variable and acting on it (like throwing an InterruptedException) is the (only!) way to do it properly.
Marcus Lindblom
+1  A: 

"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

Charles
+1. Works very well unless you have a big time-consuming op you can't split.
Marcus Lindblom