digitalmars.D.learn - D2 Singleton / Thread Local Storage issue
- sybrandy (9/62) Aug 29 2009 Hello,
- Sergey Gromov (14/22) Aug 30 2009 The thread local/shared storage doesn't seem to work well currently.
- sybrandy (4/4) Aug 30 2009 Thanks for the info. I was hoping that there would be a different
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? Thanks in advance. Caseyimport std.stdio; import core.thread; class Simple { string buff; public: static Simple instance; void setMsg(string msg) { buff ~= msg; } string getMsg() { string temp = buff.idup; buff.length = 0; return temp; } private: this() {} static this() { instance = new Simple; } } class ThrTest : Thread { this() { super(&run); } private: void run() { auto var = Simple.instance; var.setMsg("foo"); writeln("message: " ~ var.getMsg()); } } void main() { Thread t = new ThrTest(); t.start(); t.join(); writeln("Finished testing Simple.d"); }
Aug 29 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.
Aug 30 2009
Thanks for the info. I was hoping that there would be a different solution, but I guess I should have expected that I may have to wait for the feature to stabilize. Casey
Aug 30 2009