On 02/13/2017 01:27 AM, Moritz Maxeiner wrote:
__gshared int a = 0;

// thread 1:
a = 1;
int b = a;
writeln(b);

// thread 2:
a += 1;

In the above, you may expect `b` to be either 1, or 2, depending on how
the cpu interleaves the memory access, but it can, in fact, also be 0,
since neither the compiler, nor the cpu can detect any reason as to why
`a = 1` should need to come before `int b = a` and may thus reorder the
write and the read.

This doesn't make sense to me. b depends on a. If I run thread 1 alone, I can expect b to be 1, no? Thread 2 can then a) read 0, write 1; or b) read 1, write 2. How can b be 0 when the writeln is executed?

An example like this makes more sense to me:

----
shared int a = 0, b = 0;

// Thread 1:
a = 1;
b = 2;

// Thread 2:
writeln(a + b);
----

One might think that thread 2 cannot print "2", because from the order of statements the numbers must be 0 + 0 or 1 + 0 or 1 + 2. But thread 1 might execute `b = 2` before `a = 1`, because the order doesn't matter to thread 1. So 0 + 2 is possible, too.

Reply via email to