How to handle a QTimer from another Thread in the MainWindow Class with a Connection and Signal and Slot ->QueuedConnection



  • Hey Guys,

    I am felling a little bit stupid, but I am not able to get it running on my own ..

    In my MainWindow class I am starting a Simulator in another Thread, with the SIGNAL of the started thread I am starting a timer, who brings me data. When the user pushes stop, the timer should stop and the thread too.
    I read several guides, which told me to emitting a signal when I pushed stop and do the connection in the simulator class, where the thread is running. I guess thats true, but I am not able to bring the MainWindow class to the Simulator class. I dont know how to handle that. I always do it like:

    classObject = new class(classObject I want to pass);
    

    I know that it is impossible to do that with my MainWindow, because I am creating these constructors there. So there must be another solution, which I dont find in the web.

    I read something from inherit MainWindow in the Simulator class. But this causes damages in my class and I still dont know what to write afterwards in the connection as the SIGNAL object.

    right now, just QObject is inherited:

    class HEGSimulator : public QObject
    {
       Q_OBJECT
    

    Thank you in advance


  • Qt Champions 2016

    Hi
    Cant you just connect the mainwindow signal to the Simulator in mainwindow ?
    No need to pass the mainwindow and let Simulator connect if mainwindow knows simulator.

    So when you create Simulator
    (pseudo code)
    Simulator * new Simulator ()
    connect(Simulator , SimulatorSignal , this , slotinmainwindow, qt::QueuedConnection ); // note QueuedConnection

    or did i miss something ?


  • Lifetime Qt Champion

    Hi,

    Shouldn't that rather be something like:

    simulator = new Simulator;
    connect(simulator, &Simulator::mySignal, this, &MainWindow::mySlot);
    connect(stopButton, &QPushButton::clicked, simulator, &Simulator::stop); 
    

    simulator being a class member of your MainWindow and stopButton either a button you created with Designer or a QPushButton you created earlier.



  • @mrjj
    @SGaist

    I thought the same, I tried it with emitting a signal in my own MainWindow::stop Method and connecting it to the stop method in the Simulator. Currently it is handled:

    hegDevice           = new HEGSimulator();
    
    connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
       connect(ui->stopbutton,             SIGNAL(clicked()),this,         SLOT(stop()));
    
    void MainWindow::stop()
    {
    //    hegDevice->stopDevice();
     //thread->quit();
    }
    

    I toggled and untoggeled everythinh in these methods, still getting the same errors...

    QueuedConnection and Direct Connection are resulting the same Output:

    After pushing the stop button:

    
    QObject::killTimer: Timers cannot be stopped from another thread
    Stopped worker process in Thread  0x15b8
    

    After closing the window:

    
    QObject::~QObject: Timers cannot be stopped from another thread
    

    @mrjj case would have a signal from the simulator, but I just get the signal from pushing the stop button.
    @SGaist
    Your first connect is also with a signal from the simulator. But the timer is in the 2nd thread in the simulator file. So I can just stop it in a method in this class?!

    Maybe I am stuck in my brain somewhere. Feels like ..



  • Crazy stuff, now it works for the push button

    connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
    
    connect(ui->stopbutton,             SIGNAL(clicked()),this,         SLOT(stop()));
    
    void MainWindow::stop()
    {
     thread->quit();
    }
    

    closing the window causes still:

    QObject::killTimer: Timers cannot be stopped from another thread
    QObject::~QObject: Timers cannot be stopped from another thread
    

    but I guess I need to implement some stuff in the destructor


  • Lifetime Qt Champion

    Where are you creating that timer exactly ?



  • @SGaist

    HEGSimulator::HEGSimulator()
    {
        _pSample    =   new Sample();
    
        _samplerate =   10;
        _xData      =   0;
        _yData      =   0;
        _iTrianglefunction=0;
    
    }
    
    HEGSimulator::~HEGSimulator()
    {
     delete _timer;
        delete _pSample;
    }
    
    void HEGSimulator::startDevice()
    {
        _timer      =   new QTimer();
         connect(_timer, SIGNAL(timeout()),this,SLOT(createSample()));
    
    //  _timer->moveToThread(this->thread()); //doesnot work so implemented in this method
        _timer->start(_samplerate);
        qDebug()<<"Starting worker process in Thread "<<thread()->currentThreadId();
    
    }
    

  • Lifetime Qt Champion

    Where/when is startDevice called ?



  • @SGaist
    Thanks for helping me:

    hegDevice           = new HEGSimulator();
    thread              = new QThread();
    thread->setObjectName("SIMULATOR");
    
    connect(ui->startButton,            SIGNAL(clicked()),this,         SLOT(start()));
    connect(thread,                     SIGNAL(started()),hegDevice,                SLOT(startDevice()),Qt::DirectConnection);
    connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
        connect(ui->stopbutton,             SIGNAL(clicked()),thread,       SLOT(quit()),Qt::QueuedConnection);
    
    MainWindow::~MainWindow()
    {
    //does not  work properly
        thread->quit();
        hegDevice->stopDevice();
        delete hegDevice;
    
    }
    void MainWindow::start()
    {
        /**
        (1) Start the hegDevice in its own Thread to let it run on their own.
        **/
    hegDevice->moveToThread(thread);                                         //(1)
        thread->start();
        qDebug()<<"MainThread "<<this->QObject::thread()->currentThreadId();
    }
    

    AND the stop out of heg simulator

    void HEGSimulator::stopDevice()
    {
        _timer->stop();
    
        qDebug()<<"Stopped worker process in Thread "<<thread()->currentThreadId();
    
    }
    


  • @KonradMD
    With direct connection, the slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.

    So my guess with:

    connect(thread,  SIGNAL(started()),hegDevice, SLOT(startDevice()),Qt::DirectConnection);
    

    you're actually creating the timer in the main thread.

    try it with Qt::QueuedConnection



  • @J.Hilk

    Right now, the connects are working I guess, but I will test your advice. If I stop the Measurement before Closing the window I get:

    MainThread  0x160c
    Starting worker process in Thread  0x150c
    Stopped worker process in Thread  0x150c
    Stopped worker process in Thread  0x160c
    

    The last line is not cool, its because of the destructor code but no Qt Message in comparison to:

    If I close the window before pressing stop:

    MainThread  0x14d4
    Starting worker process in Thread  0x12f8
    QObject::killTimer: Timers cannot be stopped from another thread
    Stopped worker process in Thread  0x14d4
    QObject::~QObject: Timers cannot be stopped from another thread
    
    

    @J-Hilk
    Your Advice with Queued Connection results in the same application output. And the _timer is in the same thread with both methods. I read that Direct is immediatly calling the slot and Queued is waiting until the normal Code is finished? So probably its risky to use direct because I dont know if the class is already moved in the thread? is that what you mentioned?


  • Lifetime Qt Champion

    Give your QTimer a parent. That way it will be moved with the worker object when calling moveToThread.



  • Hey @SGaist

    I set the HEGSimulator as parent from my _timer. And replaced the timer and the connecter in the constructor. I used _timer->moveToThread(this->thread()) to move the _timer to the Thread I am using for the class, this should work, if I interpret the output correctly. But there is a new error message and I guess its something with my emit from the main in the end. I can not figure out where exactly its placed. But it is just there, if I close te GUI.

    _timer      =   new QTimer(this);
    
    ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 1b7e7ca0. Receiver '' (of type 'HEGSimulator') was created in thread 1b87f408", file kernel\qcoreapplication.cpp, line 541
    Invalid parameter passed to C runtime function.
    Invalid parameter passed to C runtime function.
    

  • Lifetime Qt Champion

    You seem to have several timers in your code, which one are you moving exactly ?



  • @SGaist

    In my Simulator class I have just one timer for the Samplerate of my Data. In the MainWindow I have a Timer as well for my framerate, but I want to get rid of it, but it is also a problem... I am not that into QThreads right now, maybe I should read some tutorials about it again.

    Would you initialise the Timers in the Main Window and move them to the thread and controll the connections in main window instead of directly in the class?

    Thanks for your advices!


  • Lifetime Qt Champion

    It really depends on how you manage your thread.

    The current Qt 5 documentation about QThread is way better than before so it should help you get on track.



  • I think this case can be marked as solved, I really dont understand the syntax completly, because I have a similar case now, more complex, but also a QTimer which should start and I always get the same Error-Message. I hope that with some time for trail and error I will understand the syntax. My solution for this case is:

    MainWindow::MainWindow()
    {
        hegDevice           = new HEGSimulator();
        simulatorThread     = new QThread();
    
        connect(simulatorThread,            SIGNAL(started()),hegDevice,                SLOT(startDevice()),Qt::QueuedConnection);
    
     connect (this,SIGNAL(stopHEGDevice()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
    
     connect(ui->startButton,            SIGNAL(clicked()),this,         SLOT(start()));
        connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
        connect(ui->stopbutton,             SIGNAL(clicked()),simulatorThread,       SLOT(quit()),Qt::QueuedConnection);
    
    }
    
    void MainWindow~MainWindow
    {
     if(simulatorThread->isRunning())
        {
            emit stopHEGDevice();
            //because of the delation of the emit I use this msleep. Debug Mode works properly without Debug the simulatorThread->quit was faster than the emit.
            this->thread()->msleep(100);
    
    delete hegDevice;
        }
    
        //Out of Qt Docu
        simulatorThread->quit();
        simulatorThread->wait();
    }
    
    void MainWindow::start()
    {
    qDebug()<<"MainThread "<<this->QObject::thread()->currentThreadId();
    
        hegDevice->moveToThread(simulatorThread);                                     
        simulatorThread->start();
    }
    
    HEGSimulator::HEGSimulator()
    {}
    
    HEGSimulator::~HEGSimulator
    {
    delete _timer;
    }
    
    void HEGSImulator::startDevice()
    {
    _timer      =   new QTimer();
         connect(_timer, SIGNAL(timeout()),this,SLOT(createSample()));
        _timer->start(_samplerate);
        qDebug()<<"Starting HEGDevice in Thread: "<<thread()->currentThreadId();
    }
    
    void HEGSimulator::stopDevice()
    {
     _timer->stop();
        qDebug()<<"Stopped HEGDevice in Thread: "<<thread()->currentThreadId();
    }
    

    In every case I can imagine the output is:

    MainThread  0x1754
    Starting HEGDevice in Thread:  0x63c
    Stopped HEGDevice in Thread:  0x63c
    

  • Lifetime Qt Champion

    You realise that each time you call startDevice you create a new QTimer and you only delete the last one created in your HEGSimulator destructor.

    Either create your timer in the constructor of HEGSimulator giving this as parent or check if the _timer already exist before creating a new one in startDevice. When an QObject is moved to another thread all its children are moved with it.



  • @SGaist

    I realised it, and you are right, it is not resource friendly. I changed it, and its working as well. Just quiting the main window causes some Errors.

    ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 1b6d7ca0. Receiver '' (of type 'HEGSimulator') was created in thread 1b772990", file kernel\qcoreapplication.cpp, line 541
    Invalid parameter passed to C runtime function.
    Invalid parameter passed to C runtime function.
    

    I will fix that and update this thread, I guess my mistake is something with quiting the thread, because the HEGDevice is already stopped.
    Just beside, is my MainWindow Start function right and does this connecter make sense?

    connect(ui->stopbutton,             SIGNAL(clicked()),simulatorThread,       SLOT(quit()),Qt::QueuedConnection);
    
    MainThread  0x14dc
    Starting HEGDevice in Thread:  0x17e0
    Stopped HEGDevice in Thread:  0x17e0
    MainThread  0x14dc
    Starting HEGDevice in Thread:  0x1620
    Stopped HEGDevice in Thread:  0x1620
    

    it looks like I created a new thread...?! I just wanted to stop the current one and let it wait until a new work is incoming. Or is it better to stop them and recreate?

    I am a little bit confused, because I just created a Pointer named simulatorThread and if I quit this one, a new one is coming out of nowhere?
    Can you help me to understand or give me some advice :)

    Thanks in advance :)



  • @KonradMD
    Let me ask you, why do you want to "pause" the Thread and pick it up later again?

    From what I understood of your previous posts, you used the Worker approach, that means when your Threaded obejcts/classes have nothing to do the QThread will take up - next to- no ressources.



  • @J.Hilk

    I thought that it will still took some CPU. But indeed you are right, I just let it run, with nothing to do, because I stopped the qtimer.

    I changed that, Thanks :)



  • I get this Error,

    ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread edad48. Receiver '' (of type 'HEGSimulator') was created in thread 1bc55888", file kernel\qcoreapplication.cpp, line 541
    Invalid parameter passed to C runtime function.
    Invalid parameter passed to C runtime function.
    

    just in Debug Mode and exactly when I want to

    delete hegDevice;
    

    in which the Thread was running.

    My solution for that is:

    connect(simulatorThread,SIGNAL(finished()),hegDevice,SLOT(deleteLater()));
    

    and no

    delete hegDevice
    

    in the Destructor anymore


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.