Search code examples
.netsynchronizationlockingreaderwriterlockcross-process

Cross-process read-write synchronization primitive in .NET?


Is there a read/write locking mechanism that works across processes (similar to Mutex, but read/write instead exclusive locking)? I would like to allow concurrent read access, but exclusive write access.


Solution

  • No. As Richard noted above, there is no such out of the box mechanism in .NET. This is how to implement it using a mutex and a semaphore.

    Method #1 is described in http://www.joecheng.com/blog/entries/Writinganinter-processRea.html, quoting:

    // create or open global mutex
    GlobalMutex mutex = new GlobalMutex("IdOfProtectedResource.Mutex");
    // create or open global semaphore
    int MoreThanMaxNumberOfReadersEver = 100;
    
    GlobalSemaphore semaphore = new GlobalSemaphore("IdOfProtectedResource.Semaphore", MoreThanMaxNumberOfReadersEver);
    
    public void AcquireReadLock()
    {
      mutex.Acquire();
      semaphore.Acquire();
      mutex.Release();
    }
    
    public void ReleaseReadLock()
    {
      semaphore.Release();
    }
    
    public void AcquireWriteLock()
    {
      mutex.Acquire();
      for (int i = 0; i < MoreThanMaxNumberOfReadersEver; i++)
        semaphore.Acquire(); // drain out all readers-in-progress
      mutex.Release();
    }
    
    public void ReleaseWriteLock()
    {
      for (int i = 0; i < MoreThanMaxNumberOfReadersEver; i++)
        semaphore.Release();
    }
    

    An alternative would be:

    Read locking - as above. Write locking as follows (pseudocode):

    - Lock mutex
    - Busy loop until the samaphore is not taken AT ALL:
    -- wait, release.
    -- Release returns value; 
    -- if value N-1 then break loop.
    -- yield (give up CPU cycle) by using Sleep(1) or alternative
    - Do write
    - Release mutex
    

    It must be noted that more efficient approach is possible, as here: http://en.wikipedia.org/wiki/Readers-writers_problem#The_second_readers-writers_problem Look for the words "This solution is suboptimal" in the article above.