Broken TLS?

Dechcaudron via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 27 12:19:48 PDT 2016


I keep getting data from within a struct shared across threads 
for apparently no reason: the code is the following:

import std.stdio;
import std.concurrency;
import core.thread : Thread, thread_joinAll;

struct Foo
{
     int a;
     int b;

     this(int a, int b)
     {
         this.a = a;
         this.b = b;

         writefln("Constructor -> a: %s, b: %s, &a is %s, &b: %s, 
this: %s, Thread: %s",
          this.a, this.b, &this.a, &this.b, &this, 
Thread.getThis.id);
     }

     ~this()
     {
         writefln("Final values were a:%s, b:%s", a, b);
     }

     void ping() shared
     {
         import core.time: dur;

         writefln("a: %s, b: %s, &a: %s, &b: %s, this: %s, Thread: 
%s",
          a, b, &a, &b, &this, Thread.getThis.id);

         a = 0;
         b = 0;
     }

     void fire()
     {
         spawn(&explode);
     }

     void explode() shared
     {
         ping();
     }
}

void main()
{
     auto a = Foo(1, 2);
     a.fire();

     thread_joinAll();
}

What I get on screen is the following:
Constructor -> a: 1, b: 2, &a is 7FFD5D9E3928, &b: 7FFD5D9E392C, 
this: 7FFD5D9E3928, Thread: 139774191032448
a: 1, b: 2, &a: 7FFD5D9E3928, &b: 7FFD5D9E392C, this: 
7FFD5D9E3928, Thread: 139774178481920
Final values were a:0, b:0

So effectively, the thread spawned does have access to the 
original struct and is able to modify it.

Is there anything I'm doing wrong? I won't lie, data sharing is 
the only thing about D I don't find quite usable yet. Can anybody 
help me out on this?


More information about the Digitalmars-d-learn mailing list