在.net框架中创建对象是线程安全的操作


Module Module1
    Dim test As testclass
    Sub Main()
        test = New testclass(0)
        Task.Run(AddressOf thread1)
        Task.Run(AddressOf thread2)
        Console.WriteLine("running")
        Do
            Dim a = read()
            Console.ReadLine()
            Console.WriteLine($"aa is{a.aa},bb is{a.bb}")
        Loop
    End Sub
    Class testclass
        Public aa%
        Public bb%
        Sub New(v%)
            aa = v
            bb = v

        End Sub
    End Class
    Sub thread1()
        Dim c = 0
        Do
            test = New testclass(c)

            c += 1
        Loop
    End Sub
    Sub thread2()
        Do
            Dim a = test
            If a.aa <> a.bb Then
                Console.WriteLine("chatcha")
            End If
        Loop
    End Sub

End Module

考虑上面的vb代码,一个线程正在创建对象,另一个线程正在读取这些对象,一个线程是否有可能读取一个构造值,以便在编译器未优化的情况下在控制台上显示“ catcha” (我已经在x64窗口上进行了测试,没有检测到中间读取,但是我不知道在内存模型较松散的其他cpu架构或其他情况下是这种情况)

longxin0118 回答:在.net框架中创建对象是线程安全的操作

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3156205.html

大家都在问