Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a List<T> thread safe if you are only altering values?

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.

like image 324
NibblyPig Avatar asked Oct 28 '25 05:10

NibblyPig


2 Answers

This would work because you are only reading from the list. You don't write to it.

like image 166
Daniel Hilgarth Avatar answered Oct 29 '25 20:10

Daniel Hilgarth


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:

  • You're not reading from memory but from disk (I/O is slow)
  • The action you're performing to manipulate the objects is slow (like in the order of milliseconds or greater, instead of simple property modification)
like image 21
Wim.van.Gool Avatar answered Oct 29 '25 19:10

Wim.van.Gool