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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

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. Thanks
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.
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.
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.
That won't work if the writing thread destroys items and you've copied references
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.