使用CAS原子增加两个整数 [英] Atomically increment two integers with CAS

查看:185
本文介绍了使用CAS原子增加两个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,可以通过compare-and-swap指令对两个整数进行原子递增。



如何完成?



(注意,一个接一个地递增整数的显而易见的解决方案不是原子的,并且将多个整数填充到一个机器字中不计数,因为它会限制可能的范围。)

解决方案

让我想到一个序列锁。不太准确(把这个从内存),但是一些沿着:



让x,y和s是64位整数。



要增加:



原子s ++

 内存屏障
原子x ++
原子y ++
原子s ++
内存障碍

阅读:

  do {
S1 = load s
X = load x
Y = load y
内存屏障
S2 = load s
} while(S1!= S2)

另请参阅 https://en.wikipedia.org/wiki/Seqlock


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.

How can this be done?

(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:

let x,y and s be 64 bit integers.

To increment:

atomic s++ (I mean atomic increment using 64 bit CAS op)

memory barrier
atomic x++
atomic y++
atomic s++
memory barrier

To read:

do {
    S1 = load s
    X = load x
    Y = load y
    memory barrier
    S2 = load s
} while (S1 != S2)

Also see https://en.wikipedia.org/wiki/Seqlock

这篇关于使用CAS原子增加两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆