0

問題 :
While ループを使用して状態をチェックし、指定された時間内にサーバーから応答が得られない場合はタイマーを使用します。

OS: Linux
SDK: QT 5.5

説明:

私はクライアント側を実装しましたが、コードには、何らかの条件(「チェックマシンが開始されました」)が真であることを継続的にチェックするwhileループがあります。この状態は、マシン Server から何らかのメッセージを受け取ると変化します。whileループを実装すると、スタックして出てこない。このフォーラムで質問を投げかけたところ、親切にも私の間違いを指摘してくれた人がいて、while ループがすべてのリソースを消費しているため、QStateMachine を使用するよう提案してくれました。

そのため、ステート マシンについて詳しく調べているときに、QCoreApplication::processEvents() に出くわしました。コードに追加すると、すべてが期待どおりに機能しますが、タイマー部分はまだタイムアウトします。今私の質問は

1) QStateMachine と QCoreApplication::processEvents() の違いは何ですか & どちらが優れていますか?

2) QTimer を正しく使用して、while ループの条件が規定時間内に真にならない場合、タイムアウトして 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()

外部変数を変更する場合timerは、timerStartポインタへのポインタをQTimerその関数に渡す必要があります。

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

ちなみに、はゼロに設定されることはないため、チェックif( timer )インtimerStop()はどのような場合でも意味がありません。timer

于 2015-08-28T13:14:08.177 に答える