CAS (compare and swap) algorithm to ensure atomicity

CAS is to support concurrent first CPU to provide atomic test and set operation, usually run on the operating unit. Operand is V, A, B.

CAS operation includes three operands - a memory location (V), is expected to original value (A) and the new value (B).

If the memory location of the original value matches the expected value (V == A), then the processor will automatically update the position values ​​for the new value.

Otherwise, the processor does nothing.

In either case, it returns the value of the position before the CAS instruction. (In some special cases will be returned only if CAS CAS is successful, without extracting the current value.) CAS effectively explains, "I think the location should contain the value V A; If you include this value, the B put in this position; otherwise, do not change the location, you can just tell me the value of this position. "

CAS algorithms aim is to ensure atomicity (a complete operating "read - modify - write") 

Computer To modify a value of three-step process:

①, it reads this value to their own separate memory.

②, the update operation (modify value) in its own separate memory.

③, then the modified value after the rewrite in memory

This is a complete process.

 In this process, if there are other threads on top of the thread you want to modify values ​​change operation, it will lead to the correct value is not written.

CAS simulated example of an algorithm:

/*
 * 模拟 CAS 算法
 */
public class TestCompareAndSwap {
 
	public static void main(String[] args) {
		final CompareAndSwap cas = new CompareAndSwap();
		
		for (int i = 0; i < 10; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					int expectedValue = cas.get();
					boolean b = cas.compareAndSet(expectedValue, (int)(Math.random() * 101));
					System.out.println(b);
				}
			}).start();
		}
		
	}
	
}
 
class CompareAndSwap{
	private int value;
	
	//获取内存值
	public synchronized int get(){
		return value;
	}
	
	//比较
	public synchronized int compareAndSwap(int expectedValue, int newValue){
		int oldValue = value;
		
		if(oldValue == expectedValue){
			this.value = newValue;
		}
		
		return oldValue;
	}
	
	//设置
	public synchronized boolean compareAndSet(int expectedValue, int newValue){
		return expectedValue == compareAndSwap(expectedValue, newValue);
	}
}

 

Published 242 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41813208/article/details/103946028