If I have a list with 100 items, and 4 threads that alter 25 items each such that they never alter each other's items, will the list be 'thread safe' ie. will it work as expected?
An example would be, you have an array of 1000 cats and their 'name' property is blank as they haven't been named. You want to go through and name them all, but you want it to be multithreaded. So you create 10 threads and tell each one to only do 0-99, 100-199 etc. and set them off.
This would work because you are only reading from the list. You don't write to it.
As the others have already pointed out, the act of reading is thread-safe by nature. Concurrency only becomes an issue when certain threads want to write and/or others want to read from a resource.
Having said that, I can add that if you use a collection for this purpose, the use of an explicit readonly collection (or simply the use of an IEnumerable) can be considered. .NET now offers these readonly collections out of the box. This makes it more explicit that you're only reading from the collection.
And on a side-note: I don't know the context of your requirements, and perhaps you just oversimplified the problem here, but serial access to in-memory collections is blazingly fast, so you having multiple threads read from the collection is only well founded in the following cases:
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