0
class myClass
{
    int a, b;

    void A() {...}

    void B() {...}
};

myClass myObject;

If I make an object of myClass called myObject which has methods A and B, is it thread safe to call myObject's A from one thread and its B from another thread? Assuming A and B don't share any objects or access the same part of memory. What about accessing different members of myObject like a and b?

Is it the same in Java and C++?

As far as I understand, a program is thread safe as long as different threads don't access the same part of memory at the same time. Here I pass myObject's reference to both threads but they are accessing different methods and members which ultimately have different addresses.

SMMB
  • 107
  • 6
  • 1
    I don't know for Java, but in c++ thread safety needs to be implemented explicitely. – πάντα ῥεῖ Jan 27 '21 at 17:38
  • In C++, the rule is that if you have one or more writers to shared data, then you need synchronization. If that's not your case, then your safe. You do still have to worry about false-sharing, but that is performance issue, not a safety one. – NathanOliver Jan 27 '21 at 17:39
  • No matter what *[compiled ...]* language you might be talking about, the term, ***"thread safe,"*** has a very specific meaning: that "any number of threads can use this facility at the same time, and it will always work." As an excellent rule of thumb, you should therefore assume that *"this-or-that is* ***not(!)*** *"thread-safe,"* unless the documentation expressly states otherwise. (There ... I have just saved you from a very-exquisite form of "debugging hell!") // Also note that ***interpreted*** languages are different "because of the interpreter's implementation." – Mike Robinson Jan 27 '21 at 19:18

0 Answers0