Project Description
ReaderWriterLocker which cannot be hard locked. Meant to replace ReaderWriterLock and ReaderWriterLockSlim so you don't have to be bothered by upgrade locks.

Original located at http://readerwriterlockalt.codeplex.com/. Forked from jpmikkers' ReaderWriterLockAlt.

It supports .NET 2.0+. And in the future, this code will be provided in VB.net, C# .net, and pending library selection, gnu gcc C++.

 

Example Syntax
VB.NET
' Untested code...

Imports System
Imports System.Threading
Imports System.Collections.Generic

Dim Lock    As New ThreadSafeReaderWriterLock(True)
Dim List      As New List(Of Integer)(New Integer {0,5,0,4,0,3,0,2,0,1})
Dim IsBusy As Integer = 0

Public Sub InitalizeThreads()
  For Index As Integer = 0 To 25
    Interlocked.Increment(IsBusy)
    ThreadPool.QueueUserWorkItem(FunctionToRunInMultipleThreads, Index)
  Next

  While IsBusy > 0
    Thread.Sleep(500)
  End While
End Sub

Public Sub FunctionToRunInMultipleThreads(threadContext As Object)
  Dim threadIndex As Integer = CInt(threadContext)
  Console.WriteLine("thread {0} started...", threadIndex);

  Using ReadLock As IDisposable = Lock.GetReadLock()
    ' Iterate through list
    For Index As Integer = 0 To List.Count - 1
      List(Index) += Index
    Next

    ' Upgrade read lock to write lock.  Yes.  It is this simple.
    Using WriteLock As IDisposable = Lock.GetWriteLock()
      For Index As Integer = 0 To List.Count - 1
        List.Add(List(Index))
      Next
    End Using

    ' Iterate through list
    For Index As Integer = 0 To List.Count - 1
      Console.WriteLine("List value: {0}, on thread {1}.", List(Index), threadIndex)
    Next
  End Using

  Interlocked.Decrement(IsBusy)
End Sub

Last edited Sep 15, 2010 at 12:21 AM by TamusJRoyce, version 3