www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Trying to understand how "shared" works in D

reply "Sparsh Mittal" <sparsh0mittal gmail.com> writes:
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?


#!/usr/bin/env rdmd

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
parent reply "Matej Nanut" <matejnanut gmail.com> writes:
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
parent "Sparsh Mittal" <sparsh0mittal gmail.com> writes:
Thanks a lot. VERY VERY helpful.
Jan 31 2013