I am currently learning about multithreading. I have a book (Exam 70-536 self-paced training kit) which gives an example about multi-threading.
So I have tried this (taken from the book). The code is as follows:
Imports System.Threading
Public Class FastMemFile
Private _file As String = "Hello, World!"
Private _rwl As New ReaderWriterLock
Public Sub ReadFile()
_rwl.AcquireReaderLock(10000)
For i As Integer = 1 To 3
Console.WriteLine(_file)
Thread.Sleep(1000)
Next
_rwl.ReleaseReaderLock()
End Sub
Public Sub WriteFile()
_rwl.AcquireWriterLock(10000)
_file += " It's a nice day!"
_rwl.ReleaseWriterLock()
End Sub
End Class
Public Class SlowMemFile
Private _file As String = "Hello, World!"
Public Sub ReadFile()
SyncLock Me
For i As Integer = 1 To 3
Console.WriteLine(_file)
Thread.Sleep(1000)
Next
End SyncLock
End Sub
Public Sub WriteFile()
SyncLock Me
_file += " It's a nice day!"
End SyncLock
End Sub
End Class
As you see the classes do exactly the same, except that the FastMemFile uses a ReaderWriterLock and the SlowMemFile uses SyncLock. The calling code looks like this:
Imports System.Threading
Module Module1
Sub Main()
Dim m As New SlowMemFile
Dim t1 As New Thread(New ThreadStart(AddressOf m.ReadFile))
Dim t2 As New Thread(New ThreadStart(AddressOf m.WriteFile))
Dim t3 As New Thread(New ThreadStart(AddressOf m.ReadFile))
Dim t4 As New Thread(New ThreadStart(AddressOf m.ReadFile))
t1.Start()
t2.Start()
t3.Start()
t4.Start()
End Sub
End Module
The FastMemFile is indeed much faster than the SlowMemFile. However the results I get seems to be completely random (for both classes). Sometimes I get "Hello, World!" 9 times, sometimes I get "Hello, World! It's a nice day" 9 times, and sometimes I get "Hello, World!" 3 times and "It's a nice day!" 6 times and yet other times it's the other way around...
Does this have anything to do with me having an ultra-fast Intel Core i7?
And if this is so then how can I make sure my code does actually execute in the right order, but on seperate threads? I want to make sure the code executes correctly no matter the processor speed.
Some code examples are appreciated, but some good articles that address the problem are actually more welcome.