8

How to create a Thread Safe global TList ?

unit Unit1;
interface
uses
    ...;
type
  TForm1 = class(TForm)
  procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;
  global_TList: TList; // Not thread safe?

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
// something
end;

end.

I have two threads, which can write to global_TList , but as I know, it's not thread safe.

So how to make it safe?

Delphi 2010, Indy 10, Win7

jmp
  • 2,456
  • 3
  • 30
  • 47
  • related: http://stackoverflow.com/questions/302583/how-can-i-implement-a-thread-safe-list-wrapper-in-delphi – Warren P Dec 07 '11 at 00:43
  • See [Delphi Help](http://docwiki.embarcadero.com/CodeExamples/XE2/en/TThreadList_(Delphi)) for an example how to work with a TThreadList. – LU RD Dec 07 '11 at 01:14

1 Answers1

19

Use TThreadList. Problem solved.

dthorpe
  • 35,318
  • 5
  • 75
  • 119
  • 1
    That's what TThreadList was built for. TThreadList is not a list of threads, it is a TList that is safe to use from multiple threads at the same time. – dthorpe Dec 07 '11 at 00:53
  • Thanks !! I tough it's some locker.. But there is no propertie .count , how to count ? – jmp Dec 07 '11 at 01:03
  • 2
    You can't access the count of the contents of the list while other threads could potentially be updating the list, changing the count. That means the count number you just obtained is meaningless. Instead, TThreadList provides a "check out" model - you can only obtain the protected list object by locking the threadlist. No other threads can use the threadlist until you unlock it. Be sure to use try/finally to ensure you always unlock what you lock. – dthorpe Dec 07 '11 at 01:22
  • 5
    Don't write code like threadlist.LockList.Count. That's asking for trouble - it's easy to forget that you have to call threadlist.UnlockList to release the lock so other threads can use the list. call threadlist.LockList and assign the result to a variable, start a try block and use the list variable in the try block, and close with a finally which calls threadlist.UnlockList – dthorpe Dec 07 '11 at 01:27