Issue :
Using While loop to check condition and use timer if doesnt get response from server within specified time.
OS: Linux
SDK : QT 5.5
Description:
I have implemenetd a client side and in code there is while loop which continously checks for some condition( "check machine has started") to be true. This condition changes when it get some message from machine Server . When I implemented while loop it get stuck in it and doesnt come out. I fired Question in this forum and someone was kind enough to point me my mistake and he suggested I should use QStateMachine as my while loop is eating all my resources.
So while googling more about state machine I bumped into QCoreApplication::processEvents(). When i added it in my code everything works as expected but the timer part still timesout. Now my question is
1) What is difference between QStateMachine and QCoreApplication::processEvents() & which one is better.
2) How to correctly use QTimer so that if condition in while loop doesnt become true within stipulated time just timeout and skip while loop.
void timerStart( QTimer* timer, int timeMillisecond )
{
timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( noRespFrmMachine( ) ) ) ;
timer->start( timeMillisecond );
}
void timerStop( QTimer* timer )
{
if( timer )
{
timer->stop();
}
}
void noRespFrmMachine( )
{
vecCmd.clear();
}
void prepareWriteToMachine()
{
// Some other code
// check if Machine has started we will get response in MainWindow and
// it will update isMachineStarted so we can check that
QTimer *timer ;
timerStart( timer, TIMEOUT_START ); // IS THIS RIGHT??
while( isMachineStarted() == false ) // getMachineRunning-> return isMachineStarted ??
{
// do nothing wiat for machine server to send machine_started signal/msg
QCoreApplication::processEvents(); // added this one and my aplication is responsive and get correct result
}
if( isMachineStarted() == true )
{
// if we are here it mean timer has not expired & machine is runing
// now check for another command and execute
timerStop( timer );
while( vecCmd.size() > 0 )
{
QString strTemp = returnFrontFrmVec();
setStoreMsgFrmCliReq( strTemp );
reconnectToServer();
}
}
}
}
The line timerStop( timer );
should cause segmentation fault. The function timerStart
does not change the local variable timer
of prepareWriteToMachine()
, so that variable contains undefined junk.
If you want to change external variable timer
in timerStart
you should pass pointer to pointer to QTimer
into that function:
void timerStart(QTimer**timer, int timeMillisecond)
{
*timer = new QTimer(this);
...
}
By the way, the check if( timer )
in timerStop()
does not make sense in any case, since timer
is never set to zero.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.