Example

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 that 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

You may expand this example by placing more write locks within read locks, read locks within write locks. And copying this, attaching 1 to the end of all variables so it is working using a different lock around a different list in parallel to this list. Or you can run the unit test included with the source code (found in downloads), which does this.

Back to Home Page

Last edited Sep 15, 2010 at 5:00 AM by TamusJRoyce, version 5

Comments

No comments yet.