簡體   English   中英

在模擬器中計數連接和命令(Delphi 7 / Windows XP)

[英]Counting connections and commands in a simulator (Delphi 7/Windows XP)

我在模擬器中進行測試,以測試發送到服務器的連接和命令。 模擬器具有一些計數器,例如已發送命令總數,已成功發送命令,已失敗發送命令,連接嘗試,成功連接等。

我使用的代碼如下:

procedure TALClient.SendCommand;
begin
  Try
    dlgMain.IncrementIntConx; //Increments conn attemps
    FTCP.Connect(1000);
    If FTCP.Connected Then
      Begin
        dlgMain.IncrementConections;  //increments successfully connections

        try
          dlgMain.IncrementIntSendCommand;  //Increments command sent attemps (A)
          FTCP.SendCmd(FCmd.FNemo + ' ' + FCmd.FParams);  // (Z)
          dlgMain.IncrementSendComm;  //Increments sent Commands (B)

          try
            FParent.CS.Acquire;
            FParent.FStatistic[Tag, FCmd.FTag].LastCodeResult := FTCP.LastCmdResult.NumericCode;
            FParent.FStatistic[Tag, FCmd.FTag].LastMsgResult := FTCP.LastCmdResult.Text.Text;
            FParent.CS.Release;
            if ((FTCP.LastCmdResult.NumericCode) = (497)) then
              Synchronize(UpdateCorrectCounters)  //increments successfully responds from server
            else
              Synchronize(UpdateErrorCounters);  //increments failed responds from server
          except
            Synchronize(UpdateErrorCounters);
          end;

        except
          dlgMain.IncrementFailCommand; //increments failed commands (C)
        end;
      End
    Else
      Synchronize(UpdateErrorCounters); //Increment failed responses from sever
  Finally
    If FTCP.Connected Then
      FTCP.Disconnect;
  End
end;

我已將代碼更改為許多其他方式,但始終無法正常工作。 最大的問題是已發送命令的總數不等於成功發送的命令加上失敗發送的命令。 (在代碼中:A不等於B加C)。 在標記為(Z)的行中,有些響應我從未“看到”,也許是“丟失”的響應...

所以,我做錯了什么?

我猜您正在為模擬器使用多個線程。 在我看來,這似乎是經典的“ 丟失更新”問題。 您必須同步反增量代碼。

遞增變量不是線程安全的:

Temp := CounterValue;
// If another thread intercepts here, we've got a lost update
Temp := Temp + 1;
CounterValue := Temp;

請參閱此MSDN文章,以了解有關並發問題的更多信息。

如果僅使用計數,則可以使用Windows函數InterlockedIncrementInterlockedDecrement並且不需要任何鎖定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM