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 16:45:00 PDT 2017


On 09/11/2017 03:38 PM, Walter Bright wrote:

 > If an address is taken to a TLS object, any relocations and adjustments
 > are made at the time the pointer is generated, not when the pointer is
 > dereferenced. Hence, the pointer may be passed from thread to thread,
 > and will still point to the same object.

Since we're talking about TLS, the data is not shared. So, I think 
you're referring to an example where the value of the pointer is passed 
e.g. as a ulong. Otherwise, of course std.concurrency.spawn does not 
allow non-shared parameters.

Continuing with John Burton's example, the following program 
demonstrates your point. The address of main's TLS 'data' is passed as 
ulong and then used as an int* by other threads:

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

int data;

class Lock {
}

void display(shared(Lock) lock, ulong u) {
     synchronized (lock) {
         int *p = cast(int*)u;
         writeln("Address is ", p);
         ++(*p);
         writeln(*p);
     }
}

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

The output shows that all threads did modify the same data:

Address is 7F3E4DF5E740
1
Address is 7F3E4DF5E740
2
Address is 7F3E4DF5E740
3
3

Ali



More information about the Digitalmars-d-learn mailing list