Difference between revisions of "Atomic Operation"

From CDOT Wiki
Jump to: navigation, search
(Created page with 'Category:Computer Architecture An ''atomic operation'' is one that cannot be interrupted. These operations are typically used for acquiring locks. Consider the following cod…')
 
 
(2 intermediate revisions by the same user not shown)
Line 5: Line 5:
  
 
  if (lock == 0) {
 
  if (lock == 0) {
   lock++
+
   lock++;
 
   /* Perform exclusive action */
 
   /* Perform exclusive action */
   lock--
+
   lock--;
 
  } else {
 
  } else {
   abort()
+
   abort();
 
  }
 
  }
  
Line 19: Line 19:
  
 
GCC provides [[Compiler Intrinsics|intrinsics]] for some atomic operations.
 
GCC provides [[Compiler Intrinsics|intrinsics]] for some atomic operations.
 +
 +
(Note that in the above example, even the <code>lock++</code> statement may not be atomic - it will typically compile into the three-operation sequence "load-increment-store", and its possible that two processes or threads could each perform this operation in an interleaved fashion and increment <code>lock</code> by just one instead of two).

Latest revision as of 21:23, 9 October 2019

An atomic operation is one that cannot be interrupted. These operations are typically used for acquiring locks.

Consider the following code, intended to set a "lock" in shared memory so that only one thread or process performs a particular action at a time:

if (lock == 0) {
  lock++;
  /* Perform exclusive action */
  lock--;
} else {
  abort();
}

If another process or thread writes to the lock variable between the lock comparison (lock == 0) and setting the lock (lock++), then the lock could fail to ensure exclusive action.

There are two ways to accomplish an atomic operation:

  1. Use a single machine instruction.
  2. Tell the operating system in advance not to interrupt the operation.

GCC provides intrinsics for some atomic operations.

(Note that in the above example, even the lock++ statement may not be atomic - it will typically compile into the three-operation sequence "load-increment-store", and its possible that two processes or threads could each perform this operation in an interleaved fashion and increment lock by just one instead of two).