[Issue 17543] __gshared block modifier is ignored by static variables

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sat Jun 24 10:00:09 PDT 2017


https://issues.dlang.org/show_bug.cgi?id=17543

--- Comment #4 from ZombineDev <petar.p.kirov at gmail.com> ---
(In reply to Robert Luger from comment #3)
> This works though:
> 
> 
> import std.stdio, std.parallelism;
> 
> 
> __gshared:
> 
> 
> auto return_gshared(){
> 	
> 	class Test {
> 		bool set;
> 	}
> 
> 	return new Test();
> 
> }
> 
> 
> void main(){
> 	auto obj = return_gshared();
> 	auto t = { obj.set = true; }.task;
> 	t.executeInNewThread;
> 	t.spinForce;
> 	writeln(obj.set);
> }

__gshared has no effect in the program above (e.g. commenting it out doesn't
change the result). That's because the variable 'obj' of type 'Test' is shared
by both the main thread and the thread on which the task is executed.
One simple test to verify if a class/struct member is effectively 'static'
(i.e. shared by all instances of the current thread, or all threads (if it's
declared as either '__gshared' or 'static shared') is to check if:
* It has the 'offsetof' property, or
* If it can be accessed with the 'Type.staticMember' sytnax
(which is what I think effectively
http://dlang.org/phobos/std_traits#hasStaticMembery does)

__gshared:

auto return_gshared(){

    class Test {
        bool set;
    }

    pragma (msg, __traits(compiles, { size_t offset = Test.set.offsetof; }));
// true
    pragma (msg, Test.set.offsetof); // 16LU
    pragma (msg, __traits(compiles, { auto copyOfStaticVariable = Test.set;
})); // false

    return new Test();
}

--


More information about the Digitalmars-d-bugs mailing list