Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi TList in multithreading

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?

like image 822
Junaid Noor Avatar asked Jan 20 '13 15:01

Junaid Noor


2 Answers

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>.

like image 195
David Heffernan Avatar answered Nov 04 '22 16:11

David Heffernan


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.

like image 5
Remy Lebeau Avatar answered Nov 04 '22 16:11

Remy Lebeau