Daniel Vidić
Daniel Vidić

Reputation: 164

Does accessing a public variable/object from multiple threads produce an exception in Delphi?

If multiple threads are executing class procedure TDjelatBL.Test, is there going to be an exception due to accessing variable iPublic?

The point of my question is if accessing same variable/object/constant from two or more threads simultaneously will raise an exception. I assume that nature of change of variable/object does not change memory allocation like changing size of an array.

Closest question (comparing to this one) I have found is Is a Delphi global procedure threadsafe and Are Delphi simple types thread safe? but raising of an exception is never mentioned.

unit MTTest;

interface

uses
    System.SysUtils, System.Classes;

type

    TDjelatBL = class
    public
        class procedure Test;
    end;

var
    iPublic: Integer;
    StringList: TStringList;

implementation

class procedure TDjelatBL.Test;
var
    i: Integer;
begin
    StringList.Add('x');
    for i := 1 to 1000000000 do
    begin
        iPublic := iPublic + StringList.Count;
    end;
end;

initialization
    StringList := TStringList.Create;
finalization
    StringList.Free;

Upvotes: 2

Views: 1100

Answers (1)

David Heffernan
David Heffernan

Reputation: 613322

Simultaneous read/modify/write actions on an integer variable will not result in exceptions.

There is a classic data race condition with your code. But there will be no exception. Use InterlockedIncrement to avoid the data race.

Using a global variable for the string list is a problem. Expect exceptions when two threads try to use that single variable simultaneously. That variable should be a local variable, and then that particular problem is resolved.

Upvotes: 4

Related Questions