سؤال

Can one generally assume thread-safety for get-methods if not otherwise noted in the documentation of a method? Or is it the other way round that one should never assume thread-safety if not otherwise noted? What do you think?

Edit:

Assume a class

class InfoClass {
  public:
    void Init();
    int  GetInfo();
    void Free();
};

Calling Init() once, GetInfo() from a threaded context, and Free() after the threaded operations have ended.

هل كانت مفيدة؟

المحلول

Thread-safety always requires extra work, so the only thing you can safely assume is the opposite - in the absence of a direct support the thread-safety is not supported.

Explanation:

Suppose you have a getter for a simple 64-bit long long and are running on a 32-bit architecture. While the computer is fetching the second half of that long 64-bit value (having just been done with the first half) another thread updates that second half and now what you have is an inconsistency - thus it's not thread-safe.

Edit (to match the edit in the question):

(side note - the way you presented your class is making it unusable as all the members are private)

If you do not have any access methods that change the state of your class after it's been built then you can assume thread-safety. But it's still a sloppy slope as later on someone who doesn't know about your assumption may add a setter to the class and have a wonderful journey in a random-error debugging experience ;)

نصائح أخرى

I think you should assume the method is not thread-safe if not said otherwise.

Actually I don't see any reason to assume a method is thread-safe by default.

A get method COULD be thread-safe, but again not necessarily. If there is a class:

class A {
    int value;

    int getValue() {
        return value;
    }

    void processValue() {
        value += 2;
        value = value*2;
    }
}

In the above code, getValue is clearly not thread-safe as it might be called when another thread is at the second line in processValue and hence the variable value being in an inconsistent state. So, the getter here is re-entrant (again, this might not be so), but still not thread safe.

As others have mentioned on this thread, unless specified, assume that it is not thread safe.

If the variable is getting updated using set method when you call get method the result will be garbage. So unless specified, thread safety can not be assumed.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top