Friday 15 March 2013

c# - Lockfree Read value after Interlocked.Exchange? -


We say that we have such a class:

  public square fu {private bar Bar = new bar (); Public Zero DoStuffInThread1 () {var old = Interlocked.Exchange (ref bars, new times); // It's okay to work with old / everything, I'm sure I have the last time) Public Zero Other Stuff Fertrate 2 () {// How do I ensure that I have the latest referee I bar.Something (); }}  

And say we have two threads, one is working on DoStuffInThread1 and another OtherStuffFromThread2 .

How do I ensure that thread2 always sees the latest bar? Unstable does not help and I do not want old school locks, should I have a way of reading the correct value of the bar with the MEM barriers / interlocked in any way?

You are missing points ...

Unless you do Do the following:

  Public Zero Other Stuff Fertrate 2 () {While (true) {// How do I ensure that I have the latest refract here // mem cahces etc. times etc some (); }}  

Something like this is quite impossible, almost every method you can use on OtherStuffFromThread2 () thread1 to wait for a ready There will be indirect memory access .. For example, see some methods ... // Implicit MemoryBarrier here :-) // How do I ensure that I have the latest ref I / mem cahces etc bar some (); }

If you really want to read the value of a variable, you can read a volatile variable and then read your variable (or read the same volatile variable twice) ). Why? Because a volatile reading acquires the synthetics, which means that it can not be changed later with the memory operation, see:

Reading a volatile region is a volatile is read. A volatile read "Acquisition of economics"; It is that it is guaranteed to be before any reference to memory occurring in sequence sequence.

If you do this:

  Private static is myslassilityl fieldthinkbestatic; Private Ent Effeilinintrade;  

and then

  var useless = myuselessvolatilefieldthatcanbestatic; Var iwanttoknow = thefieldiwanttoread;   

thefieldiwanttoread will contain a value that will read a new after myuselessvolatilefieldthatcanbestatic

Note that without a synchronization primitive, it will be difficult to find out when myuselessvolatilefieldthatcanbestatic will be :-), but:

  while (true) { Var useless = myuselessvolatilefieldthatcanbestatic; Var iwanttoknow = thefieldiwanttoread; // some code goes here}  

At least now you can use your while (true) : -)


No comments:

Post a Comment