简体   繁体   中英

When using CAS (Compare And Swap), how do I ensure the old value is actually old?

Consider the following:

    int grab_next_target(int* target) { 
            do {    
                    /* Intention: store current value of *target into old, so as  
                       to ensure that old never changes */ 
                    int old = *target; 
                    /* get new value based on old -- note that old is assumed not to change here */ 
                    int new; 
                    if (1 == old) { /* imagine that old is 1 so new is now 20 */ 
                            new = 20; 
                    } else if (2 == old) { 
                            new = 300; 
                    } else if (3 == old) { 
                            new = -20; 
                    } else if (4 == old) { 
                            new = 400; 
                    } 
                    /* but the compiler has optimized 
                       old to just read from *target, so *target could be 
                       changed by another thread to be 4.  The CAS will succeed 
                       and now target will hold the wrong value (it will hold 20, instead of 400)  */ 
            } while (!AO_compare_and_swap(target, old, new)); 
    } 

I need a way to read *target into a local variable and ensure that the local variable does not get optimized away to simply be *target. Is volatile an answer?

Yes, that (and exactly that) is what volatile does.

int grab_next_target(volatile int *target) {
    ...
    int old = *target; // Guaranteed to access "target" exactly once
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM