0

问题:
如果在指定时间内没有从服务器获得响应,则使用 While 循环检查条件并使用计时器。

操作系统: Linux
SDK: QT 5.5

描述:

我已经实现了一个客户端,并且在代码中有一个 while 循环,它不断检查某些条件(“检查机器已启动”)是否为真。当它从机器 Server 收到一些消息时,这种情况会发生变化。当我实现 while 循环时,它卡在其中并且不会出来。我在这个论坛上解雇了 Question,有人很好地指出了我的错误,他建议我应该使用 QStateMachine,因为我的 while 循环正在吃掉我所有的资源。

因此,在谷歌搜索更多关于状态机的信息时,我遇到了 QCoreApplication::processEvents()。当我在我的代码中添加它时,一切都按预期工作,但计时器部分仍然超时。现在我的问题是

1) QStateMachine 和 QCoreApplication::processEvents() 有什么区别 & 哪个更好。

2)如何正确使用QTimer,使while循环中的if条件在规定时间内不成立,只是超时并跳过while循环。

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();
                }
            }
        }
    }
4

1 回答 1

0

该行timerStop( timer );应该导致分段错误。该函数timerStart不会更改 的局部变量timerprepareWriteToMachine()因此该变量包含未定义的垃圾。

如果要更改外部变量timertimerStart则应将指向该函数的指针传递给QTimer该函数:

void timerStart(QTimer**timer, int timeMillisecond)
{
    *timer = new QTimer(this);
    ...
}

顺便说一句,签if( timer )timerStop()在任何情况下都没有意义,因为timer它永远不会设置为零。

于 2015-08-28T13:14:08.177 回答