views:

704

answers:

3

I have this design. I could not achieve what I need:

  • B is inherited from A.
  • A is inherited from QThread.

My goal is restart(re-run) to "worker" thread when it has finished its task. I intend to call the worker thread destructor for this approach because, it takes memory from heap. I need to clean-up all the related variables.

How can I achieve this?

int main()
{
   // re-start start
    A* worker = B::getInstance();  
    worker->start();
   // re-start end

    return a.exec();
}

Writing a for-loop is not a solution. Because, I need to learn worker thread is stopped completely. I tried using worker->wait(). But it does not work.

A: 

I don't fully understand your question, but if you allocate the thread and you have to restart it again once it's completed, you can do the following:

to check:

  • either set a variable in the worker thread when it's finished, and let have the main thread poll the variable for being set. When this happens, it means that the thread is finished.
  • or, have your worker thread call postEvent() so that it post a user-defined event into the event queue. This event will then be collected by the main thread, and act accordingly.

to restart:

  • either throw away the worker thread object completely and create a new one
  • or have the cleanup code in a private cleanup() method which is invoked:
    • you run the thread (first thing it does)
    • in the destructor
    • make it public and use it by hand if you want to grant this possibility (dangerous, if called while the thread is running)
Stefano Borini
A: 

The general rule in RAII (Resource Acquisition Is Initialization) is that the code that acquires a resource is responsible for ensuring it is released. Thus, your worker thread should terminate after releasing all resources it has acquired.

The general style of the main program will be:

  • Initialize that which needs initializing
  • Inside a 'forever' loop,
  • Initialize the worker thread.
  • Let it run free.
  • Main thread can either do its delegation work (handing tasks to the worker)
  • Or just wait for the worker to finish
  • And repeat.

Alternatively, the main thread can still run in the forever loop, but recognizes when a delegatable task has arrived and at that point, initialize the worker thread and give it the specific task. This allows for as many worker threads as there are incomplete delegatable tasks. You might need to throttle the number so that you don't have too many incomplete tasks.

Jonathan Leffler
+1  A: 

How about using QThread's signal finished()?

jpalecek