The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 4,262 other subscribers

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

4 Responses to “Sometimes a race condition is in just two lines of code”

  1. 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/

  2. 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.

  3. Peter said

    Similar reading (C#) in Eric Lippert’s blog post: https://blogs.msdn.microsoft.com/ericlippert/2009/04/29/events-and-races/

  4. 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.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.