Previous | Next --- Slide 34 of 44
Back to Lecture Thumbnails
mattlkf

Throwing this out as a possible solution for atomic increment:

void atomic_incr(int* addr){

while(1){

int x = *addr;
if(atomicCAS(addr, x, x + 1) == x) break;

}

}

apadwekar

General strategy for using compare and swap: 1. read value and do computation on the value 2. try to compare and swap with the value you read 3. if the swap doesn't go through repeat 1 and 2 until you are able to swap

jocelynh

Brief clarification on something that gave me pause--in the atomic_min implementation, we loop while the compare-and-swap does not return the old value we read earlier because if it differs, that means that someone else has changed addr and we need to check the new value that has been written before performing a min operation.

mattlkf

@kapalani Oh right, we need to increment *addr by x, not by 1. oops! thanks for pointing that out.

I'm not sure if the change you suggested works though - *addr may have different values inside that line if it is written to by other threads.

Also we should be using "==", not "!=", right? As @jocelynh explained.

So, edited code:

void atomic_incr(int* addr, int x){

   while(1) {
      int old = *addr;
      if (atomicCAS(addr, old, old + x) == old) break;
   }
}
bamboo
void lock_init(int *addr){
   // done on init 
   *addr = 1;
}

void lock(int *addr) {
   while(atomicCAS(addr,1,0) == 0); 
}

void unlock(int *addr) {
    *addr = 1;
}
kayvonf

@bamboo. Your code is correct! However, typically we use the value 1 to indicate a locked state. Your implementation uses the value 0 to do so.

@bamboo, @mattlkf. I edited the formatting of your posts to show how to write code in markdown (just intent 4 spaces)