Wednesday, December 01, 2004

How to increment a variable?

Came across this article that explains how a simple variable increment instruction, like count++, can give weird results in concurrent environments. C is a fairly low-level language, and one might expect this instruction to be directly translated into a memory increment instruction for the underlying processor by the compiler. But this is true only for CISC architectures like x86 and not for RISC architectures like PowerPC. PowerPC has a load-store design and to increment the value of the variable, you need to first load the contents of the memory into a register, increment the value in the register, and then store it back. Thus if the code is reentered while the variable is being incremented, strange results can emerge. The author explains PowerPC instructions that implement a policy of reservation on memory addresses, and allow one to write truly atomic code.

So, the title for this post should instead be, How to update memory in concurrent environments? But the current one got you reading... didn't it :-)

No comments: