Delphi TList in multithreading Delphi TList in multithreading multithreading multithreading

Delphi TList in multithreading


That is not safe without synchronisation. The reading threads can be in the middle of a read at the same time as the writing thread modifies the list. And modifying the list can mean reallocating the underlying memory.

The RTL provides the TThreadList class for such a scenario. Each thread, both writing and reading threads, need to wrap all access to the list in LockList and UnlockList pairs.

var  ThreadList: TThreadList;//declared in some shared location....//each thread accesses the list like this:var  List: TList;....List := ThreadList.LockList;try  .... do stuff with Listfinally  ThreadList.UnlockList;end;

If you are using a Delphi that supports generics there is a generic version, TThreadList<T>.


As others have stated, TList by itself is not thread-safe. If you are worried about the overhead of using TThreadList (which uses a critical section internally), then have a look at wrapping your existing TList code with a TMultiReadSingleWriteSynchronizer, or even a Win32 SRW lock.