Mutual exclusion for read/write - but no sync/lock for concurrent reads

I

illegal.prime

So I have a container of objects that I don't want to iterate across
when I'm modifying it. I.E. I lock on adds and deletes to the
container - so that my traversals of it don't result in concurrency
issues.

However, what do I need to do to allow multiple threads to traverse
the container without synchronization/mutual-exclusion - but ensure
that synchronization/mutual-exclusion is there when the container is
trying to be both changed and traversed?

My guess would be to use semaphores - but the only synchronization
mechanism I've used in C# is the lock statement. What do I need in
this scenario?

Here is some pseudo code:

class Foo
{
private List<Bar> mMyContainer = new List<Bar>();

public void DoSomething (int i)
{
lock (mMyContainer)
{
((Bar)mMyContainer).DoSomething();
}
}

public void AddElement(Bar bar)
{
lock (mMyContainer)
{
mMyContainer.Add(bar);
}
}
}

Novice
 
J

Jon Skeet [C# MVP]

So I have a container of objects that I don't want to iterate across
when I'm modifying it. I.E. I lock on adds and deletes to the
container - so that my traversals of it don't result in concurrency
issues.

However, what do I need to do to allow multiple threads to traverse
the container without synchronization/mutual-exclusion - but ensure
that synchronization/mutual-exclusion is there when the container is
trying to be both changed and traversed?

That's what ReaderWriterLock is for. However, be warned that unless the
reading/writing actually take quite a long time, the benefit of
allowing concurrent reading may be outweighed by the extra cost of
ReaderWriterLock itself.
 
Top