PDA

View Full Version : Signal isn't catched in Thread



kahlenberg
5th February 2016, 13:48
I want to fire a signal to an Object that moved into a QThread, it doesn't receive fired "startFlash" signal. Below is my code:



//mainwindow.cpp
.....
ThreadFlasher = new QThread;
flasher = new Flasher(0);
.....
connect(ThreadFlasher, SIGNAL(started()), flasher, SLOT(process())); // This works, process function in flasher runs
connect(this, SIGNAL(stopThread()), flasher, SLOT(stopThread()));
connect(this, SIGNAL(startFlash()), flasher, SLOT(startFlash()));
...

void MainWindow::on_pushButtonFW_clicked()
{
emit startFlash();
}
void MainWindow::on_openButtonConnect_clicked()
{
flasher->moveToThread(ThreadFlasher);
ThreadFlasher->start();
}


....
//Flasher.cpp

void Flasher::process()
{
while(run)
{
msleep(10); // I think There is not enough time to get variable startFlashing?
if(startFlashing)
{
FLASH_StartFlash();
startFlashing = false;
}
}
emit finished();
}

void Flasher::startFlash()
{
startFlashing = true;
}
void Flasher::stopThread()
{
run = false;
}

code_err
5th February 2016, 14:58
Ok then, I tell You how I solved this problem. I will explain to You what seems to be going on in Your code.
When You start process() function which is a slot You block event loop in QThread because of while loop. I did the same.
The solution is to use code whith QEventLoop and QTimer. Here is a loop You can try.



void
QEventLoop loop;
QTimer timer;
timer.setSingleShot(true);
QObject::connect(&timer, SIGNAL(timeout), &loop, SLOT(quit());

startLoop:
{
timer.start(20);
loop.exec()


// (...)



}
if(run)
{
gotoLoop:
}

anda_skoa
5th February 2016, 15:59
The solution is to not block the thread's event loop.

This looks like there is no need for process() at all, this could just call FLASH_StartFlash() in startFlash()

Cheers,
_