Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a List<t> be accessed by multiple threads?

I am planning to share a List between multiple threads. The list will be locked during a changes, which happen infrequently. Is there a thread safety issue if multiple iterations are made from different threads through the list simultaneously?

like image 624
Behrooz Karjoo Avatar asked Dec 21 '10 21:12

Behrooz Karjoo


People also ask

Why are lists not thread safe?

In fact, by default, classes are not thread-safe. Being thread-safe would mean that any operation modifying the list would need to be interlocked against simultaneous access. This would be necessary even for those lists that will only ever be used by a single thread. That would be very inefficient.

Can multiple threads access the same object?

Only one thread can execute a method or block of code protected by the same object reference.

Is reading a list thread safe?

Yes, List<T> is fine to read from multiple threads concurrently, so long as nothing's writing.

Can multiple threads access the same array?

The answer is no. Each array element has a region of memory reserved for it alone within the region attributed the overall array.


2 Answers

List<T> is not thread-safe generally. Having multiple readers will not cause any issues, however, you cannot write to the list while it is being read. So you would need to lock on both read and write or use something like a System.Threading.ReaderWriterLock (which allows multiple readers but only one writer).

like image 87
Harry Steinhilber Avatar answered Oct 13 '22 13:10

Harry Steinhilber


It can be read from multiple threads simultaneously, if that's what you're asking. Consider a reader-writer lock if so.

like image 28
Gabe Avatar answered Oct 13 '22 13:10

Gabe