0

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.

Stav Alfi
  • 13,139
  • 23
  • 99
  • 171

1 Answers1

1

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.

nos
  • 223,662
  • 58
  • 417
  • 506
  • by the article this is only a memory read opertion. I still dont get it why? – Stav Alfi Oct 11 '13 at 12:56
  • Because the write to d is completely irrelevant to what the article discusses. – nos Oct 11 '13 at 12:57
  • by that, currect me if im wrong, memory reading count as local variable gets any kind of value(number,char,aother variable). and memory writing count as wrting to thread-shared memory location any kind of value(number,char,aother variable). – Stav Alfi Oct 11 '13 at 13:03
  • 1
    @StavAlfi No. Reading means the system have to read memory location somewhere. Writing means it has to write memory location somewhere. If you do `a = b` , the system need to read from `b`, because it needs to fetch the value of `b`. Once it has read the value of `b` it writes that value to `a`. If you do `a = 5`, it would normally be regarded as only writing to `a` , as `5` is already a value. This has nothing to do multithreading. But the article discusses what happens when there is thread shared memory, and for that purpose, only the parts that read/writes shared variables are of intererest – nos Oct 11 '13 at 13:07