6
votes

Is it safe to use TList in a multithreaded application which is accessed by all the other threads but only one thread writes to it. the scenario is

A unique TList to each thread which only that thread will write to while other threads will just access it to fetch data from it.

Is it safe?

2

2 Answers

11
votes

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 List
finally
  ThreadList.UnlockList;
end;

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

5
votes

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.