質問

I think I am terribly confused on the scope and practice of thread safety. MSDN documentation and many commentators commonly say that instance methods are often not threadsafe. But if if a class instance is created and destroyed in only one thread, do we still worry about thread safety?

Consider the following. We create a thread and, while inside that thread, create multiple instances of TestMethod, which modifies the instance's class variables. Is the entire class instance thread safe, including the shared class variable?

Class InstancedClass
    Private testVar As Integer
    Private Shared sharedTestVar As Integer

    Public Sub TestMethod()
        'Do stuff to modify testVar/sharedTestVar
    End Sub
End Class

Public Class CallingClass
    Public Sub Main()
        Dim t As New Threading.Thread(Sub()
                                          Dim newInstance As New InstancedClass
                                          newInstance.TestMethod()
                                      End Sub)
        t.Start()

        Dim t2 As New Threading.Thread(Sub()
                                          Dim newInstance As New InstancedClass
                                          newInstance.TestMethod()
                                      End Sub)
        t2.Start()
    End Sub
End Class

Summary of questions:

1.) Are class instances thread safe if they are created and destroyed entirely within a thread?

2.) Expanding on this, is all code thread safe if doesn't touch external instances, properties and variables outside the scope of the thread?

3.) If a class has no shared properties, are its shared methods thread safe?

役に立ちましたか?

解決

1) Yes, if their scope doesn't reach any farther, their methods aren't changing anything outside the instance boundaries and their shared members (if any) are thread-safe themselves (see answer 3).

2) Yes, for pretty much the same reasons as 1.

3) Yes, if whatever they do doesn't change any other objects. For example, a shared Multiply method is generally thread-safe.

他のヒント

My answer to all 3 questions would be NO:

1) No, they are not automatically thread safe, e.g. when they access/modify shared data (like in your example, with the Shared sharedTestVar variable.

2) No, if it accesses shared properties, then it's not thread safe (without any locking).

3) No. Only if it doesn't access any other shared data (e.g. another class with shared properties, or files, etc.).

As Crono1981 said Yes for all 3 questions. Each thread has its own stack and all the local variables and method arguments are stored in that stack. As long as you do not use anything outside that stack (for example: static variables) it's thread-safe.

Good article about threading: http://www.albahari.com/threading/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top