Creating immutable data and sharing it

Lutger lutger.blijdestijn at gmail.com
Tue Sep 21 02:17:10 PDT 2010


I'm still a bit fuzzy on how to create immutable data and when said data is safe 
to share across threads.

To begin with, there is .idup, string literals and constructors of immutable 
objects. Those can be safely shared, no problem, right?

But then, the spec mentions casting to immutable is ok if you do not have any 
mutable aliases left (http://www.digitalmars.com/d/2.0/const3.html):

char[] s = ...;
immutable(char)[] p = cast(immutable)s.dup; // ok, unique reference

I do not understand how that works with sharing. Since immutable data is 
implicitly shared but the data that p refers to is allocated on the TLS, how can 
you share this? I always thought that threads do not have access to each others 
TLS at all?

Finally a practical question: when you have a data structure that is too complex 
to create in a constructor, want to create it and then make it immutable, what 
is the current way to go about this? If it is created by one thread, would it be 
ok to type it as __gshared, cast to immutable and then send a message to other 
threads? Is __gshared required in this case? 



More information about the Digitalmars-d-learn mailing list