Search code examples
multithreadingdelphitlist

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?


Solution

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