[英]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函数InterlockedIncrement
和InterlockedDecrement
并且不需要任何锁定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.