我了解 COM 中多线程单元和单线程单元之间的区别。
请看下面的代码:
'VB.NET
Imports Project1
Imports System.Threading
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim t1 As New Thread(AddressOf PersonTest.Test2)
Dim t2 As New Thread(AddressOf PersonTest.Test2)
Dim t3 As New Thread(AddressOf PersonTest.Test2)
t1.Name = "Test1"
t2.Name = "Test2"
t3.Name = "Test3"
t1.Start()
t2.Start()
t3.Start()
End Sub
End Class
Public Class PersonTest
Public Shared Sub Test2()
Try
Dim c1 As Class1
c1 = New Class1
For test3 As Integer = 0 To 10000
For test As Integer = 0 To 10000
Dim test2 As Short = c1.Add(CShort(test))
If test2 <> test + 1 Then
MsgBox("Problem here")
End If
Next
Next
MsgBox("finished")
Catch ex As Exception
End Try
End Sub
End Class
Public Class Person
Public id As Integer
End Class
'VB6 - Project1.vbp,class1
Public Test2 As Integer
Public Function Add(ByVal TestParameter As Integer) As Integer
Test2 = TestParameter + 1
Add = Test2
End Function
根据我所阅读的内容,我希望出现“MsgBox(“这里的问题”)',因为多个线程可能会不同步地更改 Person.ID 的值,但是我已经多次测试过这个程序,它从来没有发生了。我了解线程“没有任何保证”。上面的代码会在理论上引起问题吗?如果答案是否定的,那么如何修改代码以引起问题?我正在尝试学习如何编写线程安全代码,为了做到这一点,我必须首先了解代码如何成为线程不安全的。