0

I use a QtConcurrence to run a function in a separated thread but I want to stop, pause or kill this thread but I can't. I read this:

Note that the QFuture returned by QtConcurrent::run() does not support canceling, pausing, or progress reporting. The QFuture returned can only be used to query for the running/finished status and the return value of the function.

Can I do this in any other way?

My function is:

void MainWindow::on_imprimirButton_clicked()
{
        if(filename.length() == 0){
            ui->consolaBrowser->append("Error. Debe seleccionar un fichero.");
        }else if(!filename.contains(".txt")){
            ui->consolaBrowser->append("Fichero erroneo. Debe seleccionar un archivo de tipo G-CODE.");
        }else{

            imprimiendo=1;

            *future= QtConcurrent::run(Imprimir,filename.toUtf8().data());

            imprimiendo=0;
        }
}
amurcia
  • 801
  • 10
  • 26
  • 2
    you should never need to "kill" a thread. You just need to set a flag somewhere that causes the long running process to stop. – paulm Feb 19 '14 at 12:41

1 Answers1

1

I think the QtConcurrence solution is not very nice. It is often suggested, but has no advantage over a good implementation with threading library (e.g. QThread). The sample below shows one possibility to stop your thread. If you set the variable m_bBreak true somewhere in your main program, then the thread stops. In a similar way you can get the current thread progress too.

int foo(bool* bStopper) {
  if(*bStopper)
    return 0;

  // Do code here

  return 1;
}

void QThread::run() {
  m_iErrors = foo(&m_bBreak);
  // Handle errors
}
dgrat
  • 2,214
  • 4
  • 24
  • 46
  • You can also set `qApp` properties as flags. No need to declare a variable. – user1095108 Feb 19 '14 at 13:32
  • Can you make an example? – dgrat Feb 19 '14 at 13:34
  • `qApp->setProperty("myFlag", true)`, check with `qApp->property("myFlag").toBool()`, you must `#include `. – user1095108 Feb 19 '14 at 13:41
  • And how a potentially extern function should stop execution if you set a flag in your GUI? – dgrat Feb 19 '14 at 14:00
  • Just set the flag. In the thread, probably in a loop, a conditional statement will see it and break out of the loop. Thread will end automatically. – user1095108 Feb 19 '14 at 14:03
  • :) If you call a function in your thread, you can send try to finish the thread, but usually if you do it the clean way, the function called in the thread tries to finish first. To achieve return in the function you have to use shared memory! – dgrat Feb 19 '14 at 14:09
  • shared memory is cool, but only for `IPC`. Atomic flag is another alternative. – user1095108 Feb 19 '14 at 14:17
  • 1
    I gave one example with QThread. There you just need to overload the run function. But many other Threading libraries work the same. – dgrat Feb 19 '14 at 14:37