What exactly shared means?

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 2 03:47:46 PST 2015


I always think that shared should be use to make variable global 
across threads (similar to __gshared) with some synchronize 
protection. But this code doesn't work (app is stuck on _aaGetX 
or _aaRehash ):

shared double[size_t] logsA;

void main() {

     auto logs = new double[1_000_000];

     foreach(i, ref elem; parallel(logs, 4)) {
         elem = log(i + 1.0);
         logsA[i]= elem;
     }
}


But when I add synchronized block it is OK:

shared double[size_t] logsA;

void main() {

     auto logs = new double[1_000_000];

     foreach(i, ref elem; parallel(logs, 4)) {
         elem = log(i + 1.0);
         synchronized {
             logsA[i]= elem;
         }
     }
}


More information about the Digitalmars-d-learn mailing list