Hi

Well... i am trying to create a simple example on how to do syncronization
of threads using System.Threading.ReaderWriterLock.

As you probably know, you can read and write to the resource (critical section),
just aquiring a lock to it. My simple example, just have a class with 2 methods,
one to read and other to write. The main, when the programm stats, will loop
19 times and will create threads. According to the loop number, it will read
or write to the critical section.

Although, this is not working. I can read once (one thread). Then it writes
(another thread). But, the second time another thread tried to read, they
will read all...not "one by one". Although the writer lock is doing that.

Please see the code below and say somthing about. Thnks

Imports System.Threading
Module Module1

Sub Main()
Dim recurso As New CriticalSection() 'new instance of the class
Dim i As Integer

'loop and create threads
For i = 0 To 18

'if odds we will read the resource (critical section)
If i Mod 2 <> 0 Then
Dim threads As New Thread(AddressOf recurso.Read)
threads.Name = i
threads.Start()
Else 'otherwise, write
Dim threads2 As New Thread(AddressOf recurso.Write)
threads2.Name = i
threads2.Start()
End If
Next

End Sub

End Module

'this is the CRITICAL SECTION where the threads will try to read/write
Class CriticalSection

'object
Private rwLock As New ReaderWriterLock()

'to read the critical section
Public Sub Read()
rwLock.AcquireReaderLock(Timeout.Infinite)
Try
Console.WriteLine("LENDO o recurso com a thread " & Thread.CurrentThread.Name)
Thread.Sleep(5000)
Console.WriteLine("Fim da leitura...")
Finally

rwLock.ReleaseReaderLock()

End Try
End Sub

'to write to the CS
Public Sub Write()
rwLock.AcquireWriterLock(Timeout.Infinite)

Try
Console.WriteLine("ESCREVENDO no recurso com a thread " & Thread.CurrentThread.Name)
Thread.Sleep(2000)
Console.WriteLine("Fim da escrita...")
Finally
rwLock.ReleaseWriterLock()
End Try
End Sub

End Class