| Previous | Home | Next |
Introduction of Synchronization
Synchronization is particularly important when threads access the same data; it’s surprisingly easy to run aground in this area.
Synchronization constructs can be divided into four categories:
- Simple blocking methods
- Locking constructs
- Signaling constructs
- No blocking synchronization constructs
Synchronization in Threads
Synchronization is needed in thread when we have multiple threads that share data, we need to provide synchronized access to the data. We have to deal with synchronization issues related to concurrent access to variables and objects accessible by multiple threads at the same time.
Imports System.Threading
Module Module1
Class Program
Shared Sub Main()
Console.WriteLine("-----> Multiple Threads ---->")
Dim p As New Printer()
Dim Threads As Thread() = New Thread(2) {}
For i As Integer = 0 To 2
Threads(i) = New Thread(New ThreadStart(AddressOf p.PrintNumbers))
Threads(i).Name = "Child " & i
Next
For Each t As Thread In Threads
t.Start()
Next
Console.ReadLine()
End Sub
End Class
Class Printer
Public Sub PrintNumbers()
For i As Integer = 0 To 4
Thread.Sleep(100)
Console.Write(i & ",")
Next
Console.WriteLine()
End Sub
End Class
End Module
Why we use Lock keyword
lock(object) is used to synchronize the shared object.
Syntax
SyncLock objecttobelocked objecttobelocked.somemethod() End SyncLock
objecttobelocked is the object reference which is used by more than one thread to call the method on that object.
The lock keyword requires us to specify a token (an object reference) that must be acquired by a thread to enter within the lock scope.
Using of Monitor- The lock scope actually resolves to the Monitor class after being processed by the VB.Net compiler. Lock keyword is just a notation for Imports System.Threading.Monitor class.
Imports System.Threading
Imports System.Threading.Monitor
Module Module1
Class Program
Shared Sub Main(ByVal arg As String())
Console.WriteLine(" -----> Multiple Threads ----->")
Dim p As New Printer()
Dim Threads As Thread() = New Thread(2) {}
For i As Integer = 0 To 2
Threads(i) = New Thread(New ThreadStart(AddressOf p.PrintNumbers))
Threads(i).Name = "Child " & i
Next
For Each t As Thread In Threads
t.Start()
Next
Console.ReadLine()
End Sub
End Class
Class Printer
Public Sub PrintNumbers()
Monitor.Enter(Me)
Try
For i As Integer = 0 To 4
Thread.Sleep(100)
Console.Write(i & ",")
Next
Console.WriteLine()
Finally
Monitor.[Exit](Me)
End Try
End Sub
End Class
End Module
| Previous | Home | Next |