Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: None  |  size: 1.34 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. When using CAS (Compare And Swap), how do I ensure the old value is actually old?
  2. int grab_next_target(int* target) {
  3.             do {    
  4.                     /* Intention: store current value of *target into old, so as  
  5.                        to ensure that old never changes */
  6.                     int old = *target;
  7.                     /* get new value based on old -- note that old is assumed not to change here */
  8.                     int new;
  9.                     if (1 == old) { /* imagine that old is 1 so new is now 20 */
  10.                             new = 20;
  11.                     } else if (2 == old) {
  12.                             new = 300;
  13.                     } else if (3 == old) {
  14.                             new = -20;
  15.                     } else if (4 == old) {
  16.                             new = 400;
  17.                     }
  18.                     /* but the compiler has optimized
  19.                        old to just read from *target, so *target could be
  20.                        changed by another thread to be 4.  The CAS will succeed
  21.                        and now target will hold the wrong value (it will hold 20, instead of 400)  */
  22.             } while (!AO_compare_and_swap(target, old, new));
  23.     }
  24.        
  25. int grab_next_target(volatile int *target) {
  26.     ...
  27.     int old = *target; // Guaranteed to access "target" exactly once
  28.     ...
  29. }