Иллюстрированный самоучитель по VB.NET




Взаимная блокировка - часть 2


После краткого обсуждения наиболее принципиальных моментов мы покажем, как опознать ситуацию взаимной блокировки в окне потоков:

1 Option Strict On

2 Imports System.Threading

3 Module Modulel

4 Sub Main()

5 Dim Tom As New Programmer( "Tom")

6 Dim Bob As New Programmer( "Bob")

7 Dim aThreadStart As New ThreadStart(AddressOf Tom.Eat)

8 Dim aThread As New Thread(aThreadStart)

9 aThread.Name= "Tom"

10 Dim bThreadStart As New ThreadStarttAddressOf Bob.Eat)

11 Dim bThread As New Thread(bThreadStart)

12 bThread.Name = "Bob"

13 aThread.Start()

14 bThread.Start()

15 End Sub

16 End Module

17 Public Class Fork

18 Private Shared mForkAvaiTable As Boolean = True

19 Private Shared mOwner As String = "Nobody"

20 Private Readonly Property OwnsUtensil() As String

21 Get

22 Return mOwner

23 End Get

24 End Property

25 Public Sub GrabForktByVal a As Programmer)

26 Console.Writel_ine(Thread.CurrentThread.Name &_

"trying to grab the fork.")

27 Console.WriteLine(Me.OwnsUtensil & "has the fork.") . .

28 Monitor.Enter(Me) 'SyncLock (aFork)'

29 If mForkAvailable Then

30 a.HasFork = True

31 mOwner = a.MyName

32 mForkAvailable = False

33 Console.WriteLine(a.MyName&"just got the fork.waiting")

34 Try

Thread.Sleep(100) Catch e As Exception Console.WriteLine (e.StackTrace)

End Try

35 End If

36 Monitor.Exit(Me)

End SyncLock

37 End Sub

38 End Class

39 Public Class Knife

40 Private Shared mKnifeAvailable As Boolean = True

41 Private Shared mOwner As String ="Nobody"

42 Private Readonly Property OwnsUtensi1() As String

43 Get

44 Return mOwner

45 End Get

46 End Property

47 Public Sub GrabKnifetByVal a As Programmer)

48 Console.WriteLine(Thread.CurrentThread.Name & _

"trying to grab the knife.")

49 Console.WriteLine(Me.OwnsUtensil & "has the knife.")

50 Monitor.Enter(Me) 'SyncLock (aKnife)'



Содержание  Назад  Вперед