On 9/24/2011 6:42 PM, Peter Alexander wrote:
On 24/09/11 2:39 PM, Rainer Schuetze wrote:
Is c.id thread-safe? no! Is it constant? no! How does this help in
multi-threaded applications that access c?
It is thread safe. globId is a thread-local variable.
sorry, I noticed this mistake in my example too late. Using shared(int)
still compiles:
shared(int) globId;
class C
{
@property id() immutable { return ++globId; }
}
int main()
{
immutable(C) c = new immutable(C);
return c.id;
}
Please notice, that I have also changed "const" to "immutable".
It's still thread-safe (++ is atomic) and you still don't modify c.
You need 'pure' if you want a consistent value, in which case the code
would be rejected.
It *is* constant (the C object isn't modified) put it isn't *pure* (the
return value isn't consistent).
Yes, that's my point. What is actually guaranteed by the type system to
a thread that works on an instance of type immutable(C)? It is not
thread safety or constancy when reading properties, that would require
them to be pure.
As I said above, it is thread-safety, although in this instance you
don't even need the immutable, the shared(int) guarantees the thread
safety.
Sorry for the bad example, here's one that is not thread-safe, and where
the invariant can fail in a multi-threaded environment:
shared(int) globId;
class C
{
invariant() { assert((globId & 1) == 0); }
@property int id() immutable
{
globId = globId + 1;
globId = globId + 1;
return globId;
}
}
But the details whether the operation happens to be thread safe or not
is irrelevant, thread-safety is not guaranteed by the type system with
immutable.