Question

Im sure my title is not perfect so let me clear my self.

by this article : http://msdn.microsoft.com/en-us/magazine/jj863136.aspx ,

void Print()
 {
  int d = _data;     // Read 1
  if (_initialized)  // Read 2
    Console.WriteLine(d);
  else
    Console.WriteLine("Not initialized");
}

why does Read 1 count as only reading and not as writing too? I mean, in the end the '_data' content is writen to 'd'.

I hope you understood what Im asking.

Était-ce utile?

La solution

int d = _data; is indeed a read and a write. But the write is to the local, on the stack, variable d, and is not of interest for the discussion there.

What's of interest is the order of read/writing from the member variable _data when there are several threads accessing the same object, and therefore accessing the same memory. For the local d variable, each thread have their own stack, and there's no multithreaded issues regarding accessing d in these examples.

The article discusses the _data variable, not the d variable. Whenever someone reads/writes to _data, that's the interesting piece, as that's where memory reordering in regards to multi threading is something one must be aware of. That int d = _data also writes to d is completely irrelevant.

By the comment // Read 1, it is implied that we're talking about _data - and there's no write to _data on that line of code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top