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

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

问题描述

显然,可以使用比较和交换指令原子地递增两个整数.

如何做到这一点?

(请注意,一个接一个地递增整数的明显解决方案不是原子的.另外,将多个整数填充到一个机器字中也不算数,因为它会限制可能的范围.)

解决方案

让我想起一个序列锁.不是很准确(从记忆中提取)但大致如下:

让 x、y 和 s 是 64 位整数.

增加:

atomic s++(我的意思是使用 64 位 CAS op 的原子增量)

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

阅读:

做{S1 = 负载 sX = 负载 xY = 负载 y记忆障碍S2 = 负载 s} 而(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天全站免登陆