CodePlexProject Hosting for Open Source Software
' 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
Last edited Sep 15, 2010 at 12:45 AM by TamusJRoyce, version 10
ReaderWriterLock Alternative