Qt World Summit: Register Today!


How to stop function execution



  • Hi,

    I have 2 thread, the first is the main app thread, and the second one is a dedicated thread for time consuming functions.

    My app emit a signal to start a function in the second thread. A waiting message box pop in the window of the first thread.

    My question is how can i cancel the execution of the function in the second thread ?
    I don't want to stop and exit the thread (because i would have to reload a lot of DLLs ), i just want to exit a function (where there is a lot of loops).

    Thx


  • Lifetime Qt Champion

    Hi
    Often you would teach the actual code how to quit on demand.
    if you have many loops etc then you cant exit cleanly if they are not
    designed to exit premature.

    for (int c=0; c< max && !Terminated; c++ )
    xxx

    Unless u check if to exit then loops will run fully.

    So question is to u want to really cancel the operation or simply just kinda kill the tread? (which u dont as far as i understand)

    So for me it sounds like you want the function to be able to exit and not so much the tread as such.



  • Hi and thank you for helping me,

    Yes that's it, i don't want to stop the thread, only a function.
    Then the second thread wait for a new signal from the main thread.

    I don't want to kill the thread because i'm only creating threads at the begining of my program, the second thread must live until the main thread lives.



  • define a

    private:
    std::atomic_bool m_terminator
    public:
    void stopFunction(){m_terminator=false;}
    

    in the worker of the second thread. and check for its value in the loops as suggested by @mrjj
    When you need to stop the function just call stopFunction from the first thread (being atomic takes care of avoiding race conditions)


  • Lifetime Qt Champion

    @Zoptune
    So it seems that best route is to learn your long lasting functions to exit when asked?
    Im not 100% sure there is no better way so give it some hours/day to get others opinions :)



  • Thx @VRonin and @mrjj

    I'll do as you said, i think it's the best way :)

    EDIT : i can't set the topic as solved, haven't got the option in the topic tool



  • @Zoptune said in How to stop function execution:

    EDIT : i can't set the topic as solved, haven't got the option in the topic tool

    Due to a change in template you first have to convert to a question, see
    https://forum.qt.io/topic/71830/hitchhiker-s-visual-guide-to-the-qt-forum



  • Hi,
    i want to stop the proccess of sending frames when there is missing items how can i do it ?

    void MainWindow::on_SendAll_Button_clicked()
    {
        int a= m_ui->Table_CSV->model()->rowCount();
        qDebug()<<"int a= m_ui->Table_CSV->model()->rowCount()="<<a; //nombre ligne du tab
    
    
        const int rowCount = mModel->rowCount();
        const int colCount = mModel->columnCount();
        for(int ix=0; ix<rowCount; ++ix)
        {   QString item1=getValueAt(ix, 0);
            if(item1=="")
            {qDebug()<<"Missing_item1="<<item1;
            QMessageBox::warning(this,"Warning","Missing items");}
    
            for(int jx=1; jx < colCount; ++jx)
               { QString item2=getValueAt(ix, jx);
            if(item2=="")
            {
                {qDebug()<<"Missing_item2="<<item2;
                QMessageBox::warning(this,"Warning","Missing items");}
    
            }
           }
        }
    
    
    
    
        for(int i=0;i<a; i++) //R :read , W :write
        {
            QString PayloadData_R = m_ui->Table_CSV->model()->data(m_ui->Table_CSV->model()->index(i,1)).toString();
            qDebug()<< m_ui->Table_CSV->indexAt(QPoint(2,2)).row() << " and " <<  m_ui->Table_CSV->indexAt(QPoint(2,2)).column();
            qDebug()<<"PayloadData_R="<<PayloadData_R;
            QString IdData_R = m_ui->Table_CSV->model()->data(m_ui->Table_CSV->model()->index(i,2)).toString();
            qDebug()<< m_ui->Table_CSV->indexAt(QPoint(2,3)).row() << " and " <<  m_ui->Table_CSV->indexAt(QPoint(2,2)).column();
            qDebug()<<"IdData_R="<<IdData_R;
    
        if (m_canDevice)
        {
            disconnect(m_canDevice.get(), &QCanBusDevice::framesReceived,
                        this, &MainWindow::processReceivedFrames);       //disconnect champ d'envoi alors enable "processReceivedFrames" method
            QCanBusFrame frameconnect; // Declaration nv trame :de type QCanBusFrame container of a single can frame = content "frameId + payload" to send
            //QString ID = IdData_R; //Declaration nv ID :chaine de caractère
            //const uint frameId = ID.toUInt(nullptr, 16); //Declaration nv frameID :conversion de ID (chaine de caractère) to uint(unsgned int taille 16bit)
            //just changed if 101 ***
    
            if (IdData_R=="Tx"){
            QString ID = "101"; //Declaration nv ID :chaine de caractère
             qDebug() <<"Id Tx"<<ID;
            const uint frameId = ID.toUInt(nullptr, 16); //Declaration nv frameID :conversion de ID (chaine de caractère) to uint(unsgned int taille 16bit)
            //just changed if 101 ***
            frameconnect.setFrameId(frameId); //incertion de FrameId dans uint frameId
            QByteArray payloadconnect= QByteArray::fromHex(PayloadData_R.toLatin1()); //Declaration nv tab of bytes(octets)
                                          //fromHex: Renvoie une copie décodée du tableau encodé en hexadécimal hexEncoded.
            frameconnect.setPayload(payloadconnect);//incertion de FrameId dans uint frameId
            qDebug() << "payload connect to control board" << payloadconnect; //affichage en terminal payloadconnect="\xFF\x00"
    
            m_canDevice->writeFrame(frameconnect); //envoi ecriture du trame initialement crée (frameconnect) sur canDevice
    
         //   QMessageBox::information(this,"Done","connect frame sent");
            m_canDevice->waitForFramesReceived(2000); //attend reception trame 2sec snn out
            //Renvoie vrai si de nouvelles trames sont disponibles pour la lecture et que le signal framesReceived() est émis ;
            //sinon renvoie false (si l'opération a expiré ou si une erreur s'est produite).
            QCanBusFrame frametestconnect = m_canDevice->readFrame(); //read m_canDevice trame et stocage dans la nouvelle "frametestconnect"
    
            QByteArray connectRep = frametestconnect.payload();//recupération de payload du trame
    
            qDebug() << "trame de test" << connectRep;
    
            qDebug() << frametestconnect.payload() << " size reponse connect carte de commande" << frametestconnect.payload().size();
            qDebug() << frametestconnect.frameId()<<"rense connect carte de commande" << frametestconnect.payload().size();
            //Test comparaison result recu "connectRep" et resultat attendu "Testconnect"
            QByteArray Testconnect = QByteArray::fromHex("FF00");//"FF00804008000101" Dec de trame qu'il faut recupéré
    
            if( connectRep[0]==Testconnect[0]){
                qDebug() <<"Test FF good!"; //model dialogue informing
                mModel->item(i, 4)->setText("FF");//ack
                mModel->item(i, 6)->setText("Pass");//result
    
            }
            else {qDebug() <<"Test bad! connectRep"<<connectRep;
            mModel->item(i, 4)->setText("FE");//ack
            mModel->item(i, 6)->setText("Fail");//result
            }
    
        }
    
    
        }//if 101 ** changeboth send and sendall
    }
        QMessageBox::information(this,"Done","Frames are sent successfully");
    }
    


  • @imene
    This is a [old] topic about controlling a secondary thread from the main thread. What does that have to do you with your question, which does not show threads, seems to be about a CSV file, and what are "missing items" here anyway? Please create your own, new topic for this (and explain what you are asking).




  • Banned

    This post is deleted!

Log in to reply