Saturday, 24 August 2013

shared List between threads: whitin a single thread is it safe to instantiate a list referenced to the same elements?

shared List between threads: whitin a single thread is it safe to
instantiate a list referenced to the same elements?

We have this shared list, where "MyObject" represents a class whose
objects can't be modified after creation:
List<MyObject> fooList;
When .add or .remove methods (which are the only things that can alter
fooList) are called on fooList, fooList gets locked (Monitor.TryEnter...)
Each thread may do this while accessing it, while also locking fooList:
foreach (MyObject o in fooList)
{
myList.Add(o);
}
foreach (MyObject o in myList)
{
Console.WriteLine(o.ToString());
}
Is it correct to assume that the locks are present only to make sure that
fooList won't have any .add or .remove methods being called while a
foreach iteration is in progress (hence invalidating it)?
In other words, if fooList was immutable from the start of the program,
would it be safe to remove the locks?

No comments:

Post a Comment