Global Mutex
Imports System.Threading
Module Module1
Public Class MutexSample
Shared globalMutex1 As Mutex
Shared globalMutex2 As Mutex
Const Counter As Integer = 100
Shared Event1 As AutoResetEvent = New AutoResetEvent(False)
Shared Event2 As AutoResetEvent = New AutoResetEvent(False)
Shared Event3 As AutoResetEvent = New AutoResetEvent(False)
Shared Event4 As AutoResetEvent = New AutoResetEvent(False)
Public Sub do1()
Console.WriteLine("do1 started, Mutex.WaitAll(Mutex())")
Dim gMs(1) As Mutex
gMs(0) = globalMutex1
gMs(1) = globalMutex2
WaitHandle.WaitAll(gMs)
Thread.Sleep(2000)
Console.WriteLine("do1 finished, Mutex.WaitAll(Mutex())")
Event1.Set()
End Sub
Public Sub do2()
Console.WriteLine("do2 started, globalMutex1.WaitOne( )")
globalMutex1.WaitOne()
Console.WriteLine("do2 finished, globalMutex1.WaitOne( )")
Event2.Set()
End Sub
Public Sub do3()
Console.WriteLine("do3 started, Mutex.WaitAny(Mutex())")
Dim gMs(1) As Mutex
gMs(0) = globalMutex1
gMs(1) = globalMutex2
Mutex.WaitAny(gMs)
Console.WriteLine("do3 finished, Mutex.WaitAny(Mutex())")
Event3.Set()
End Sub
Public Sub do4()
Console.WriteLine("do4 started, globalMutex2.WaitOne( )")
globalMutex2.WaitOne()
Console.WriteLine("do4 finished, globalMutex2.WaitOne( )")
Event4.Set()
End Sub
Public Sub Run()
Console.WriteLine("MutexSample ...")
globalMutex1 = New Mutex(True, "MyMutex")
globalMutex2 = New Mutex(True)
Console.WriteLine(" - Main Owns globalMutex1 and globalMutex2")
Dim evs(3) As AutoResetEvent
evs(0) = Event1
evs(1) = Event2
evs(2) = Event3
evs(3) = Event4
Dim tm As MutexSample = New MutexSample()
Dim t1 As Thread = New Thread(New ThreadStart(AddressOf tm.do1))
Dim t2 As Thread = New Thread(New ThreadStart(AddressOf tm.do2))
Dim t3 As Thread = New Thread(New ThreadStart(AddressOf tm.do3))
Dim t4 As Thread = New Thread(New ThreadStart(AddressOf tm.do4))
t1.Start()
t2.Start()
t3.Start()
t4.Start()
Thread.Sleep(2000)
Console.WriteLine(" - Main releases globalMutex1")
globalMutex1.ReleaseMutex()
Thread.Sleep(1000)
Console.WriteLine(" - Main releases globalMutex2")
globalMutex2.ReleaseMutex()
End Sub
End Class
Sub main()
Dim ms As MutexSample = New MutexSample()
ms.Run()
End Sub
End Module
MutexSample ...
- Main Owns globalMutex1 and globalMutex2
do1 started, Mutex.WaitAll(Mutex())
do2 started, globalMutex1.WaitOne( )
do3 started, Mutex.WaitAny(Mutex())
do4 started, globalMutex2.WaitOne( )
- Main releases globalMutex1
do3 finished, Mutex.WaitAny(Mutex())
^CTerminate batch job (Y/N)? n