Delphi TList in multithreading
Asked Answered
R

2

6

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?

Revengeful answered 20/1, 2013 at 15:8 Comment(0)
P
11

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

Pond answered 20/1, 2013 at 15:10 Comment(5)
hmm. that never hit my mind, i thought it will be kind of safe if only one thread writes to it but never thought of the problem you just cleared up. so i should use a tthreadlist then. ThanksRevengeful
I will use indy's TIdThreadSafeList, i was just trying to somehow skip the idea of locking and unlocking. there are way many threadsafelists in the server and locking each one for an operation which will likely to happen too many times just felt too time consuming.Revengeful
This may cause lot of contention, since only one thread can access the list at any given time. Depending on the type of data stored in the list, and if the writer does not delete items, a good optimization candidate is to code the reader to lock the list just to make a copy of the contents, unlock it and then perform it's work over the copy. You can also think in a multiple reader-single writer approach in other cases.Dishonor
yeah thats what i thought i should do, i lock the list assign it to a simple tlist unlock the threadsafe list and then perform the operations on the normal tlist.Revengeful
That won't work if the writing thread destroys items and you've copied referencesPond
W
5

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.

Woodhouse answered 21/1, 2013 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.