我正在尝试创建一个竞争条件,以便更好地理解线程如何与信号量一起使用。我从MSDN中获取了Semaphore类示例并稍微修改它以在控制台应用程序中运行。
Imports System
Imports System.Threading
Module Module1
Public Class Example
' A semaphore that simulates a limited resource pool.
'
Private Shared _pool As Semaphore
Private Shared _sharedInteger As Integer = 0
<MTAThread> _
Public Shared Sub Main()
' Create a semaphore that can satisfy up to three
' concurrent requests. Use an initial count of zero,
' so that the entire semaphore count is initially
' owned by the main program thread.
'
_pool = New Semaphore(0, 3)
' Create and start five numbered threads.
'
For i As Integer = 1 To 5
Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker))
'Dim t As New Thread(AddressOf Worker)
' Start the thread, passing the number.
'
t.Start(i)
Next i
' Wait for half a second, to allow all the
' threads to start and to block on the semaphore.
'
Thread.Sleep(500)
' The main thread starts out holding the entire
' semaphore count. Calling Release(3) brings the
' semaphore count back to its maximum value, and
' allows the waiting threads to enter the semaphore,
' up to three at a time.
'
Console.WriteLine("Main thread calls Release(3).")
_pool.Release(3)
Console.WriteLine("Main thread exits.")
Console.ReadLine()
End Sub
Private Shared Sub Worker(ByVal num As Object)
' Each worker thread begins by requesting the
' semaphore.
Console.WriteLine("Thread {0} begins " _
& "and waits for the semaphore.", num)
_pool.WaitOne()
_sharedInteger += 3
Console.WriteLine("Thread {0} adds to count of {1}.", num, _sharedInteger)
Console.WriteLine("Thread {0} releases the semaphore.", num)
Console.WriteLine("Thread {0} previous semaphore count: {1}", _
num, _
_pool.Release())
End Sub
End Class
End Module
如果三个线程同时同时进入信号量,那么如何读/写_sharedInteger
没有竞争条件? _pool.WaitOne()
的函数是否阻止其他线程访问该函数与_pool.Release()
之间的任何内容?
EDIT 我也试过修改工作者循环1000000次但没有抛出错误
Private Shared Sub Worker(ByVal num As Object)
' Each worker thread begins by requesting the
' semaphore.
_pool.WaitOne()
For j As Integer = 1 To 1000000
_sharedDouble += 1
Next j
_pool.Release()
End Sub
在这种情况下使用互斥锁不是一样好吗?