我阅读了很多关于锁定机制的材料,但我仍然没有答案如何编写一个:
- 接受比退出更多的进入
- 第二个线程将等待最多 5 秒,然后它将进入临界区
以下作品。它处理多次调用ThreadA_Method1然后它(有时)后面跟着ThreadA_Method2的情况。但是有没有更好的解决方案?
Private _lock as Boolean
Private Sub ThreadA_Method1 Handles _otherDll.BeforeAction
_lock = True
' A - Critical section code 1
' ...
End Sub
Private Sub ThreadA_Method2 Handles _otherDll.AfterAction
Try
' A - Critical section code 2
' ...
Finally
_lock = False
End Try
End Sub
Private Sub ThreadB_Method
Dim stopWatch As Stopwatch = New Stopwatch()
stopWatch.Start()
While _lock AndAlso stopWatch.ElapsedMilliseconds < 5000
Thread.Sleep(100)
End While
stopWatch.Stop()
' B - Critical section code
' ...
End Sub