G
Guest
Hi Everybody,
I've got a question about ReaderWriterLock:
Let's say I want to write a function that will update an object under write
lock
both if the calling thread has a reader lock or not.
That Is, I want a function Write() that will work properly in both these
cases:
static int i=0;
static public ReaderWriterLock locker=new ReaderWriterLock();
static public void Main() {
Write(0); // write to i outside reader lock.
locker.AquireReaderLock();
Write(i*2); // write to i unside reader lock.
locker.ReleaseReaderLock();
}
The only way I could think to write the function is something like this:
static public void Write(int val)
{
System.Threading.LockCookie cookie=new
System.Threading.LockCookie();
bool upgraded=false;
if (locker.IsReaderLockHeld)
{
cookie= locker.UpgradeToWriterLock(5000);
upgraded=true;
}
else
{
locker.AcquireWriterLock(5000);
}
try
{
i=val;
}
finally
{
if (upgraded)
{
locker.DowngradeFromWriterLock(ref cookie);
}
else
{
locker.ReleaseWriterLock();
}
}
}
This seems to do the work, but the code is a bit... complicated..
Why does locker.AquireWriteLock() inside a reader lock block?
This does not make much sense to me...
Thanks,
Nadav
I've got a question about ReaderWriterLock:
Let's say I want to write a function that will update an object under write
lock
both if the calling thread has a reader lock or not.
That Is, I want a function Write() that will work properly in both these
cases:
static int i=0;
static public ReaderWriterLock locker=new ReaderWriterLock();
static public void Main() {
Write(0); // write to i outside reader lock.
locker.AquireReaderLock();
Write(i*2); // write to i unside reader lock.
locker.ReleaseReaderLock();
}
The only way I could think to write the function is something like this:
static public void Write(int val)
{
System.Threading.LockCookie cookie=new
System.Threading.LockCookie();
bool upgraded=false;
if (locker.IsReaderLockHeld)
{
cookie= locker.UpgradeToWriterLock(5000);
upgraded=true;
}
else
{
locker.AcquireWriterLock(5000);
}
try
{
i=val;
}
finally
{
if (upgraded)
{
locker.DowngradeFromWriterLock(ref cookie);
}
else
{
locker.ReleaseWriterLock();
}
}
}
This seems to do the work, but the code is a bit... complicated..
Why does locker.AquireWriteLock() inside a reader lock block?
This does not make much sense to me...
Thanks,
Nadav