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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.