Using ReaderWriterLock -- are you getting what you think you're getting?
Oh boy, more locking problems for the weekend!
Here's a more complicated lock that often gets used when it shouldn't and is avoided when it should be used. Like the other articles in this series I'll provide a bit of code and ask for comments, it's more fun that way :)
OK, here's the code:
public class MixedUsers
{
private static System.Threading.ReaderWriterLock rw =
new System.Threading.ReaderWriterLock();
private static int val1 = 0;
private static int val2 = 0;
// this method is called by many threads
public static int ComputeSomethingUseful()
{
// disregarding timeout effects for now
rw.AcquireReaderLock(-1);
int result = val1 + val2;
rw.ReleaseReaderLock();
return result;
}
// this method is called by many threads
public static int UpdateUsefully(int v1, int v2)
{
rw.AcquireWriterLock(-1);
val1 += v1; // note coordination of updates
val2 += v2; // these two sums need to happen atomically
int result = val1 + val2;
rw.ReleaseWriterLock();
return result;
}
}
Now here are the things I want you to think about:
#1 Is this a good use of ReaderWriterLock? What assumptions do you have to make about the frequency of the operations.
#2 If UpdateUsefully were the method that was called nearly always would you give the same answer?
#3 What if ComputeSomethingUseful were called almost exclusively instead, does that change your answer?
#4 Is there a different approach to solve this particular problem that might be more robust generally?
#5 What "tiny" change could I make in this problem that would make ReaderWriterLock virtually essential?