2

The following code does not complete, because second reader (tRead2) cannot acquire lock.

ReaderWriterLockSlim rw = new ReaderWriterLockSlim();

var tRead1 = Task.Run
    (
        () => rw.EnterReadLock()
    );

var tWrite = Task.Run
    (
          () =>
          {
              Thread.Sleep(1000);
              rw.EnterWriteLock();
          }
    );


var tRead2 = Task.Run
    (
        () =>
        {

            Thread.Sleep(3000);
            rw.EnterReadLock();
        }
    );

Task.WaitAll(tRead1, tRead2);

I didn't expect this situation, I thought that since writer (tWrite) cannot get the lock, then the tRead2 would be allowed to do that (and tWrite will wait till all read-mode locks are released). I interpret this unexpected behavior as a way to disallow starvation of writer.

Is there any synchronization structure that would allow tRead2 to get the lock (even if tWrite might be starved)?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
user3284063
  • 665
  • 5
  • 20
  • 4
    Note that it is described on msdn: https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim%28v=vs.110%29.aspx *A thread that tries to enter read mode blocks if there are threads waiting to enter write mode or if there is a single thread in write mode.* and *Blocking new readers when writers are queued is a lock fairness policy that favors writers.* – xanatos Apr 07 '15 at 09:15
  • *cannot acquire lock* How do you experience this? –  Apr 07 '15 at 09:15
  • @Andreas: The code does not complete. Also, when stopped while debugging the thread that tRead2 is "riding on" hangs on rw.EnterReadLock() line. – user3284063 Apr 07 '15 at 09:21
  • 2
    You could use `TryEnterWriteLock` for the writer with a time out, task delay & retry on failure. – Alex Apr 07 '15 at 09:24

0 Answers0