D2 Singleton / Thread Local Storage issue

Sergey Gromov snake.scaly at gmail.com
Sun Aug 30 09:51:16 PDT 2009


Sat, 29 Aug 2009 22:03:47 -0400, sybrandy wrote:

> Hello,
> 
> I've been learning D for some time now and I recently was trying to do 
> some work with threads, but I'm having a problem getting it to work. 
> I'm trying to create a singleton that can be accessed between threads, 
> however I get an access violation when I try to run the following code. 
>   If I make the variable "instance" shared, I get a compilation error. 
> Is there something I'm missing?

The thread local/shared storage doesn't seem to work well currently.

Your original snippet doesn't work because there is a separate
"instance" variable for every thread, but the static ctor is only
executed once, in the main thread.  The Simple.instance stays null in
ThrTest, and that thread crashes.

Making Simple.instance shared is incorrect I think because the class
must be thread-aware as well.  The correct way would be to make the
whole Simple class shared.  When I do this I still get errors though.
One in the constructor which cannot cast "this" from Simple to
shared(Simple).  Another is in main() which thinks shared is not
mutable.

I think we should wait for another couple compiler releases for this
feature to stabilize enough to be usable.


More information about the Digitalmars-d-learn mailing list