views:

193

answers:

2

I have a TObjectList that needs to be processed by several threads. Since internally TObjectList inherits from TList and TList implements its internals as an array I wonder:

Is it thread safe to access the array from different threads as long as we access different indexes?

For example, having a TObjectList called myObjectList:

start = 0; end = myObjectList.Count div 2;

Thread1:

for i := 0 to end do
  Process(myObjectList[i]);

Thread2:

for i := end + 1 to myObjectList.Count - 1 do
  Process(myObjectList[i]);
+12  A: 

Accessing the members like this is perfectly OK.
As long as you're not changing the list at the same time (e.g. adding, removing items).
If some of the underlying objects are the same, then you could have problems if they're not thread safe.

Petesh
A: 

I would consider using TThreadList, it offers Lock and Unlock methods, you can use to alter the list in a thread-safe way. If you prefer using a TObjectList, you could have a look at the code of TThreadList, and do the locking yourself by using a TCriticalSection.

Stijn Sanders
I don't really need to modify the list, just reading it so I want to avoid the burden of locking. I just wanted to confirm that, as long as you just read the list the is no problem.
Jorge Córdoba
"Just reading" is always thread safe. You only run into trouble when you start changing things in one thread while another thread is trying to use them.
Mason Wheeler