Dear all,

Even if I know that it can be dangerous to terminate a thread, I need to do it 
for my application.
The function that run into the thread is like a long linear sequence of code 
that has not been designed in a signal/slot way. Moreover, in my thread, I need 
an eventloop as I use in it some TCP or UDP  Qt sockets.

I have tried the worker approach with the following code and I did not find a 
way to terminate the thread :

For my thread class :

        1. ThreadEx::ThreadEx(QObject *parent) :
        2.     QThread(parent)
        3. {
        4. }
        5.  
        6. void ThreadEx::run()
        7. {
        8.     QThread::setTerminationEnabled(true);
        9.     exec();
        10. }

For my worker class:

        1. ObjectInThread::ObjectInThread(QObject *parent) :
        2.     QObject(parent)
        3. {
        4. }
        5.  
        6.  
        7. void ObjectInThread::run()
        8. {
        9.    int compteur = 0;
        10. //here i am using a loop instead of the long linear flow  but it is 
not a loop  in the real code
        11.     while(1)
        12.     {
        13.         qDebug() <<compteur;
        14.         compteur++;
        15.         Sleep(1000);
        16.     }
        17. }
And for my main object that starts the thread

        1. #include "mainobject.h"
        2. #include <QDebug>
        3.  
        4. MainObject::MainObject()
        5. {
        6.     m_thread = new ThreadEx();
        7.     m_object = NULL;
        8. }
        9.  
        10.  
        11. void MainObject::start()
        12. {
        13.     if(m_object)
        14.         delete m_object;
        15.  
        16.     m_object = new ObjectInThread();
        17.     m_object->moveToThread(m_thread);
        18.     
QObject::connect(m_thread,SIGNAL(started()),m_object,SLOT(run()));
        19.     m_thread->start();
        20. }
        21.  
        22.  
        23. void MainObject::stop()
        24. {
        25.     qDebug()<<"I try to stop\n";
        26.     m_thread->terminate();
        27. }The start and stop functions are slots called via a simple GUI.
Using the stop slot does nothing.

Moreover I tried the other way of using QThread that consists in inheriting the 
QThread class and overriding the run method with the code :

void ThreadEx::run()
{
    int compteur = 0;
    while(1)
    {
         qDebug() <<compteur;
         compteur++;
         sleep(1);
    }
}

In that case terminate works but I do not have an eventloop as I did not call 
the exec method.

Is this the expected behaviour ?

I am using Qt5.1 on centOS / RedHat 6.2. I have also tried this on Windows with 
no more success.


Thanks for your help,
François
_______________________________________________
Interest mailing list
Interest@qt-project.org
http://lists.qt-project.org/mailman/listinfo/interest

Reply via email to