D2 Singleton / Thread Local Storage issue
sybrandy
sybrandy at gmail.com
Sat Aug 29 19:03:47 PDT 2009
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.
Casey
> import 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");
> }
More information about the Digitalmars-d-learn
mailing list