Address of data that is static, be it shared or tls or __gshared or immutable on o/s <x>

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 11 10:48:31 PDT 2017


On 09/11/2017 01:51 AM, John Burton wrote:

 > I wrote this program :-
 >
 > import std.stdio;
 > import std.concurrency;
 >
 > int data;
 >
 > void display()
 > {
 >     writeln("Address is ", &data);
 > }
 >
 > void main()
 > {
 >     auto tid1 = spawn(&display);
 >     auto tid2 = spawn(&display);
 >     auto tid3 = spawn(&display);
 > }
 >
 > It displayed :-
 >
 > Address is 51AD20
 > Address is 51AD20
 > Address is 51F6D0
 > Address is 521AC0
 >
 > This indicated to me that a thread local variable does in fact have a
 > different address to other thread's instances of the same thread so you
 > can in fact pass the address to another thread and access it from there
 > via pointer, which is what I'd hope.

The output is deceptive. 'data' is thread-local: Every thread has its 
own copy. The following program indicates the variables are different:

import std.stdio;
import std.concurrency;
import core.thread;

int data;

class Lock {
}

void display(shared Lock lock)
{
     synchronized (lock) {
         writeln("Address is ", &data);
         ++data;
         writeln(data);
     }
}

void main()
{
     auto lock = new shared Lock();
     auto tid1 = spawn(&display, lock);
     auto tid2 = spawn(&display, lock);
     auto tid3 = spawn(&display, lock);
     thread_joinAll();
     writeln(data);
}

Sample output (yes, 64-bit build):

Address is 7F8443BCE580
1
Address is 7F843BFFF580
1
Address is 7F844441F580
1
0

 > Interesting it also (sometimes) prints one of the lines twice quite 
often.

That's a coincidence that different threads see 'data' at the same 
address value but they are still different objects. Actually, I'm 
surprised that they are reported differently. If I remember correctly, 
in the past it would report the same address. Perhaps a case of ASLR?

 > I wonder if this is the same "bug" as
 > https://issues.dlang.org/show_bug.cgi?id=17797 that doesnt even require
 > any reading? (platform is windows 7 DMD32 D Compiler v2.076.0)

I doubt it unless you get 4 addresses instead of 3.

Ali



More information about the Digitalmars-d-learn mailing list