www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Non-atomic shared allowed.

reply "Cooler" <kulkin hotbox.ru> writes:
 From TDPL (page 411)
--------------------------------------------------
The global definition
   shared uint threadsCount;

introduces a value of type shared (uint),
which corresponds to a global unsigned int in a C program.
Such a variable is visible to all threads in the system.
The annotation helps the compiler a great deal: the language 
"knows" that
threadsCount is freely accessible from multiple threads and
forbids naive access to it. For example:
void bumpThreadsCount(){
   ++threadsCount; // Error! Cannot increment a shared int!
}
--------------------------------------------------

But if we try the program with dmd 2.064.2 it will compile and 
run.
Even more the example below shows that shared(int) increment and 
decrement are not atomic:

import std.stdio, std.parallelism;

shared int i;

void inc(){
   foreach(n; 0 .. 1000_000)
     ++i;
}

void dec(){
   foreach(n; 0 .. 1000_000)
     --i;
}

void main(){
   taskPool.put(task(&inc));
   taskPool.put(task(&dec));
   taskPool.finish(true);
   writefln("i = %s", i);
}
Feb 06 2014
parent reply "Daniel Murphy" <yebbliesnospam gmail.com> writes:
https://d.puremagic.com/issues/show_bug.cgi?id=3672
Feb 06 2014
parent "Cooler" <kulkin hotbox.ru> writes:
On Thursday, 6 February 2014 at 15:35:31 UTC, Daniel Murphy wrote:
 https://d.puremagic.com/issues/show_bug.cgi?id=3672
Oh. Thank you. Looks like my googling skills are not good enough :)
Feb 06 2014