Is the following pseudocode thread-safe ?
IList<T> dataList = SomeNhibernateRepository.GetData(); Parallel.For(..i..) { foreach(var item in dataList) { DoSomething(item); } }
The list never gets changed, it's only iterated and read in parallel. No writing to fields or something like that whatsoever.
Thanks.
If a writer may be writing at the same time, List. Contains is definitely not thread safe. You'll need to wrap it and any other reads and writes with a lock.
NET Framework 4 introduces the System. Collections. Concurrent namespace, which includes several collection classes that are both thread-safe and scalable. Multiple threads can safely and efficiently add or remove items from these collections, without requiring additional synchronization in user code.
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.
To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.
Yes, List<T>
is fine to read from multiple threads concurrently, so long as nothing's writing.
From the documentation:
A
List<T>
can support multiple readers concurrently, as long as the collection is not modified.
EDIT: Note that your code doesn't necessarily use List<T>
- just an IList<T>
. Do you know the type returned by GetData()
? If you're in control of GetData()
you probably want to document that the list returned by it is thread-safe for reading, if it's actually returning a List<T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With