Sharing a variable

OK, so rule number two is "Shared structures bad". What about sharing a simple variable? Nothing can go wrong there, right? Wrong! There are actually multiple ways something can go wrong.

The program IncDec demonstrates one of the bad things that can happen. The code contains two methods: IncValue and DecValue. The former increments a shared FValue: integer; some number of times, and the latter decrements it by the same number of times:

procedure TfrmIncDec.IncValue;var  i: integer;  value: integer;begin  for i := 1 to CNumRepeat do begin    value := FValue;    FValue := value + 1;  end;end;procedure TfrmIncDec.DecValue;var  i: integer;  value: integer;begin  for i := 1 to CNumRepeat do begin    value := FValue;    FValue := value - 1; end; ...

Get Mastering Delphi Programming: A Complete Reference Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.