.NET Framework Developer Center > .NET Development Forums > Common Language Runtime > Multithreading: Can 2 different threads invoke different methods of the same object at same time
Ask a questionAsk a question
 

AnswerMultithreading: Can 2 different threads invoke different methods of the same object at same time

  • Tuesday, November 03, 2009 7:03 PMDiana4 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Folks, I have 2 questions on multithreading..

    1)Can 2 different threads invoke different methods of the same object at same time ? The different methods do not have have any common code or data they update ..

    2)Can 2 different threads invoke same method at same time as long as the method invocation does not consist of updating of any shared variables

    Thank you

Answers

  • Tuesday, November 03, 2009 7:08 PMDavid M MortonMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    1. Yes.
    2. Yes.

    That said, keep in mind, it only takes one shared variable to create a race condition.  For your question number 1, you should also make sure they don't have any common variables they use, not just updating, but retrieving values as well.  If method 1 updates variable x, and method 2 doesn't update x, but uses x, you've created a race condition. 

    For number 2, these methods would most likely be static methods, which, as long as the code within the method only relies on the input parameters, will be inherently thread-safe.  Should you modify values outside the method (perhaps a static field) the method ceases to be thread-safe, and a race condition can occur. 
    Coding Light - Illuminated Ideas and Algorithms in Software
    Coding Light WikiLinkedInForumsBrowser
    • Marked As Answer byDiana4 Tuesday, November 03, 2009 7:16 PM
    •  

All Replies

  • Tuesday, November 03, 2009 7:08 PMDavid M MortonMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    1. Yes.
    2. Yes.

    That said, keep in mind, it only takes one shared variable to create a race condition.  For your question number 1, you should also make sure they don't have any common variables they use, not just updating, but retrieving values as well.  If method 1 updates variable x, and method 2 doesn't update x, but uses x, you've created a race condition. 

    For number 2, these methods would most likely be static methods, which, as long as the code within the method only relies on the input parameters, will be inherently thread-safe.  Should you modify values outside the method (perhaps a static field) the method ceases to be thread-safe, and a race condition can occur. 
    Coding Light - Illuminated Ideas and Algorithms in Software
    Coding Light WikiLinkedInForumsBrowser
    • Marked As Answer byDiana4 Tuesday, November 03, 2009 7:16 PM
    •