Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/Write locking confusion

I'm not entirely sure how best accomplish this multi-threading scenario so any input would be appreciated.

I have one block, that reads data, that several threads can access at once. I have another block that writes data, only one thread can write at any time. Also it can't start writing as long as any thread is reading the data. Is ReaderWriterLockSlim the way to go here, will it wait for the read threads to exit before blocking the thread for writing?

like image 667
Homde Avatar asked Nov 22 '10 14:11

Homde


2 Answers

Yes, ReaderWriterLockSlim is perfect for frequent reader/infrequent writer scenarios.

The behaviour is as you guessed - single writer only, writers block until all readers are done, readers cannot access while writer is in process.

Be careful that the time you hold the lock (whether for read or write) is long enough to prevent any concurrent access, and no longer.

like image 89
Steve Townsend Avatar answered Oct 05 '22 10:10

Steve Townsend


Yes, it sounds like ReaderWriterLockSlim is what you want.

A write lock will not be acquired as long as read locks are in place. I suggest you read the documentation for a complete description of the behavior (locking queues, etc):

http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx

like image 25
Ohad Schneider Avatar answered Oct 05 '22 11:10

Ohad Schneider