' Mutex can be used with WaitHandle.WaitAll and WaitAny, and can be passed across AppDomain boundaries.
Imports System
Imports System.Threading
Imports Microsoft.VisualBasic
Class Test
Private Shared mut As New Mutex()
<MTAThread> _
Shared Sub Main()
Dim i As Integer
For i = 1 To 3
Dim myThread As New Thread(AddressOf MyThreadProc)
myThread.Name = "Thread:" + i
myThread.Start()
Next i
End Sub
Private Shared Sub MyThreadProc()
Dim i As Integer
For i = 1 To 3
UseResource()
Next i
End Sub
Private Shared Sub UseResource()
mut.WaitOne()
Console.WriteLine("{0} has entered protected area",Thread.CurrentThread.Name)
Thread.Sleep(500)
Console.WriteLine("{0} is leaving protected area",Thread.CurrentThread.Name)
mut.ReleaseMutex()
End Sub
End Class
|