原子方式增加两个整数与CAS [英] Atomically increment two integers with CAS
问题描述
显然,这是可能的原子方式增加两个整数具有比较和交换的指令。 这次谈话声称,这样的算法存在,但它看起来像它没有详细说明。
Apparently, it is possible to atomically increment two integers with compare-and-swap instructions. This talk claims that such an algorithm exists but it does not detail what it looks like.
如何才能做到这一点?
(注意,递增前一后的整数一个显而易见的解决方案是不是原子。此外,多馅成整数一体机字不计,因为它会限制可能的范围内。)
(Note, that the obvious solution of incrementing the integers one after the other is not atomic. Also, stuffing multiple integers into one machine word does not count because it would restrict the possible range.)
推荐答案
让我想到一个序列锁。不是很准确(把这个从内存),但是沿着线的东西:
Make me think of a sequence lock. Not very accurate (putting this from memory) but something along the lines of:
让X,Y和s是64位整数。
let x,y and s be 64 bit integers.
要增加:
原子小号++
(我的意思是使用64位运算CAS原子增量)
atomic s++
(I mean atomic increment using 64 bit CAS op)
memory barrier
atomic x++
atomic y++
atomic s++
memory barrier
要阅读:
do {
S1 = load s
X = load x
Y = load y
memory barrier
S2 = load s
} while (S1 != S2)
另请参见 https://en.wikipedia.org/wiki/Seqlock
这篇关于原子方式增加两个整数与CAS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!