how to safely access and modify an Array while multithreading in delphi fmx multi device platform?

  

i’m trying to manipulate a variable array of the record type, by multiple threads, and i’m not sure what i did is the right way or if there is a better safer method?

what i did is i declared a boolean variable as a lock, and when some thread want’s access to the Array it waits till the lock is off then activate the lock, and when done unlock it and let others have access.

the code for this is decalred in the implementation section


implementation

var Data : array of TData;
var Data_Lock:Boolean=false;

procedure Lock_Data();
begin
while Data_Lock = True do
sleep(1);
Data_Lock := True;
end;

procedure UnLock_Data();
begin
Data_Lock := False;
end;

procedure ClearAll();
begin
Lock_Data();
SetLength( Data, 0 );
UnLock_Data();
end;
….

the entire project is still not complete, for now this seems to work but i don’t have any knowledge of how this things work at the core, and if two threads start at the exact same time wouldn’t there be a problem?

Comments are closed.