Sometimes a race condition is in just two lines of code
Posted by jpluimers on 2019/07/30
A race condition can be this small:
if Assigned(Setting.OnChanged) then Setting.OnChanged(Setting);
If in between these lines, the value of Setting.OnChanged
becomes nil
, then you have an access violation.
It is a very slim, but real chance.
–jeroen
Stefan Glienke said
I know it’s about .NET but most of his conclusions apply to Delphi as well: https://blogs.msdn.microsoft.com/ericlippert/2009/04/29/events-and-races/
dummzeuch said
Workaround for this problem:
var
Temp: TNotifyEvent;
begin
Temp := Setting.OnChanged;
if Assigned(Temp) then
Temp(Setting);
It’s still possible that by the time the event is called ( Temp(Setting) ) the OnChanged event has been set to nil, but at least it won’t cause an AV beause Temp will still have the original value.
But of course, if the event handler itself is no longer valid (e.g. the object that implements it has been freed) there is still a chance that this might fail.
Peter said
Similar reading (C#) in Eric Lippert’s blog post: https://blogs.msdn.microsoft.com/ericlippert/2009/04/29/events-and-races/
Darian said
The slimness of the chance depends on your coding behavior. If you are assigning a value to the Setting.OnChanged event in a different thread, then the OnChanged event (or Setting itself) should have a Read/Write lock mechanism to prevent the AV. If you aren’t changing this is a different thread, then the AV likelihood goes to zero.