Wednesday, April 10, 2024

Compare and swap

 In a multiprocessor systems that several CPU share the same memory, it is important to serialize access to specific memory cell to prevent different CPU overwrites the cell from each others. 

For example, one CPU read the cell content into ALU register, add 1 and store it back to the cell. If the execution is interrupted and the value of the cell is changed by another CPU, the value stored will be overwritten by the first CoU when it resume its execution at a later time not realising the cell value has changed. 

Compare and swap a a hardware interlocking mechanism to prevent this scenario. To use it, a CPU will read the value into the register (first parameter). He CS can instruction then compare the register value with the memory location. If the compare is equal, CS will store the register value (second parameter) to the memory location. If the compare is not equal, CS will store the value at the memory location to the first parameter register. In the latter case, the program need to handle the fact that the memory value has changed and retry the CS instruction until it is successful. 

No comments: