Only const or immutable class thread local variables are allowed

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Mon Dec 9 23:41:25 PST 2013


On 10/12/13 06:33, Jonathan M Davis wrote:
> It's still essentially a singleton - it's just that it's a single instance per
> thread in that case instead of per program. And you avoid all of the
> threading-related initialization issues with singletons if it's thread-local.
> Just check whether it's null, initialize it if it is (leave it alone if it
> isn't), and then do whatever you're going to do with it.

So for example the below code as an rndGen where Random is a class, not a struct?

I think I was misled by the "Only const or immutable ..." part of the error 
message: I'd assumed that any class that actually modified its internal state 
would be disallowed as a static instance.

///////////////////////////////////////////////////////////////////////////////
ref Random rndGen() @property
{
     static Random result = null;

     if (result is null)
     {
         result = new Random;

         static if (isSeedable!(Random, typeof(repeat(0).map!((a) => 
unpredictableSeed))))
         {
             result.seed(repeat(0).map!((a) => unpredictableSeed));
         }
         else
         {
             result.seed(unpredictableSeed);
         }
     }

     return result;
}
///////////////////////////////////////////////////////////////////////////////


More information about the Digitalmars-d-learn mailing list