Creating immutable data and sharing it

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 21 06:36:15 PDT 2010


On Tue, 21 Sep 2010 05:17:10 -0400, Lutger <lutger.blijdestijn at gmail.com>  
wrote:

> 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?

idup is not safe (along with dup), it is the equivalent of a cast right  
now.  You must still ensure the data has no aliases, or the data idup'd  
consists of all value types.

See this bug report: http://d.puremagic.com/issues/show_bug.cgi?id=3550

>
> 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

This used to be the only valid way to get immutable data besides idup.

> 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?

TLS is only for global and static variables.  Data on the heap is not TLS.

-Steve


More information about the Digitalmars-d-learn mailing list