Vort3x
Vort3x

Reputation: 1828

What kind of synchronization does this code need?

I have a threaded server application that stores List<Item> dataList. There is a single writing thread that modifies, adds and removes items from the list, and multiple threads that read from this list.

What kind of synchronization is required to ensure the writes happen in order as they were called and provide maximum performance for the reads i.e. if a write is busy reads must just provide the previous value before the read.

I currently use ReaderWriterLockSlim for it's separate Read and Write locking capabilities, but it feels as though there is a lot of expensive overhead calling the ReadLocks that is unnecessary since all I want is for writes to be guaranteed in order?

As far as I understand reading reference types and value types should provide atomic access so locking is perhaps not necessary?

Performance is a big concern and it seems like optimization of my synchronization structure could improve by quite a bit.

Upvotes: 3

Views: 142

Answers (3)

Erez Robinson
Erez Robinson

Reputation: 784

ReaderWriterLockSlim isn't really needed here, unless there is a chance you cannot enter the lock for some significant reason.
A Simple Lock(syncObj) would suffice, just place locks before read/write operations.

If TryEnter is needed, we need to see your code.

Upvotes: -1

Richard Schneider
Richard Schneider

Reputation: 35477

Sounds like you have a producer/consumer pattern. In .Net 4, there is the ConcurrentQueue<T> class in the System.Threading.Concurrent namespace. You are only synchronising when adding and removing from queue.

Upvotes: 2

Samy Arous
Samy Arous

Reputation: 6814

Without synchronization, there is a chance that a read will get partial information from before and after the write operation (for ex: 30% from the old list and 70% from the new list). If this is not an issue, then you are not required to use any synchronization as long as there is one single writer.

If your list contains objects, you might prefer writing your new data into a new object then swap this new element with the inlist one. Changing a reference should be atomic unless there are some internal mechanics I don't know about.

Object temp = new Object();
temp.value = 5;
temp.name = "whatever";
list[5] = temp;

instead of:

list[5].value = 5;
list[5].name = "whatever";

Upvotes: 0

Related Questions