thoughts on immutability in D

Peter Alexander peter.alexander.au at gmail.com
Sat Sep 24 09:42:59 PDT 2011


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.



More information about the Digitalmars-d mailing list