digitalmars.D.learn - Trying to understand how "shared" works in D
- Sparsh Mittal (30/30) Jan 31 2013 I wrote this code. My purpose is to see how shared works in D. I
- Matej Nanut (8/8) Jan 31 2013 First of all, "const" is usually used as just a bridge between
- Sparsh Mittal (1/1) Jan 31 2013 Thanks a lot. VERY VERY helpful.
I wrote this code. My purpose is to see how shared works in D. I create a global variable (globalVar) and access it in two different threads and it prints fine, although it is not shared. So, can you please tell, what difference it makes to use/not-use shared (ref. http://www.informit.com/articles/article.aspx?p=1609144&seqNum=3). Also, is a global const implicitly shared? import std.stdio; import std.concurrency; import core.thread; const int globalConst = 51; int globalVar = 17; void main() { writefln("Calling Function"); spawn(&test1, thisTid); writefln("Wait Here "); spawn(&test2, thisTid); writefln("End Here "); } void test1(Tid owner) { writefln("The value of globalConst here is %s", globalConst); writefln("The value of globalVar here is %s", globalVar); } void test2(Tid owner) { writefln("The value of globalConst here is %s", globalConst); writefln("The value of globalVar here is %s", globalVar); }
Jan 31 2013
First of all, "const" is usually used as just a bridge between immutable and plain types. You should probably use "immutable" there. As for sharing, immutable variables are implicitly shared, since they can never change (const variables CAN change somewhere else in the program). Your globalVar gets copied to each of the thread's heaps though. If you change it in one, you won't see the difference in the other.
Jan 31 2013