原子比较,多处理器,C/C ++(Linux) [英] Atomic compare, Multi-Processor, C/C++ (Linux)

查看:63
本文介绍了原子比较,多处理器,C/C ++(Linux)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多处理器系统上的共享内存x中有一个变量.

I have a variable in shared memory x on a multi-processor system.

void MyFunction(volatile int* x) {
  if (*x != 0) {
     // do something
  }
}

其他进程(可能在不同的处理器上)将使用gcc内置的原子操作(例如__sync_bool_compare_and_swap等)写入x.

Other processes (possibly on different processors) will be writing to x using gcc built-in atomic operations such as __sync_bool_compare_and_swap etc.

我认为我遇到了一些缓存并发问题,有时x最终用新值更新之前需要花费一些时间.

I think I'm running into some cache concurrency issues where sometimes it takes a bit of time before x finally gets updated with the new value.

如果存在这样的事情,我想要的是一种atomic_compare(不进行交换)?或原子阅读".最快的方法是什么?(避免使用互斥锁,锁等)

What I want is a kind of atomic_compare (without the swap), if such a thing exists? Or an "atomic read". What's the fastest way to do this? (avoiding mutexes, locks, etc.)

谢谢

我刚刚意识到,有些棘手的解决方法是使用__sync_val_compare_and_swap并使用一个我知道永远不会出现的值.这样可以解决问题吗?(有没有更清洁的方法?)

I just realized a somewhat hackish workaround would be to use __sync_val_compare_and_swap with a value that I knew it could never be. Would that solve the issue? (Is there a cleaner way?)

推荐答案

新的C标准C11具有 _Atomic 数据类型和用于处理此数据的操作.该标准尚未实现,但是gcc和clang接近它,它们已经实现了功能.实际上,函数 __ sync_bool_compare_and_swap 就是其中的一部分.我已经将其包装到 P99中的标头集中,以便您进行编程已经具有C11接口.

The new C standard, C11, has _Atomic data types and operations to deal with this. This standard is not yet implemented, but gcc and clang are close to it, they already implement the functionality. And in fact the function __sync_bool_compare_and_swap is part of it. I have wrapped that into a set of headers in P99 that let you program already with the C11 interfaces.

要执行所需操作的C11函数将是 atomic_load ,或者如果您对连贯性 atomic_load_explicit 有特殊要求.正如您所怀疑的那样,毫不奇怪,P99将其映射到 __ sync_val_compare_and_swap(& x,0,0)上.然后,如果您查看在大多数体系结构上生成的汇编程序,则在 x 成为 int 的情况下,这将仅通过简单的加载操作进行转换.但这不是语言所能保证的,而是由编译器知道这些事情并合成保证是原子性的指令.

The C11 function to do what you want would be atomic_load or if you have particular requirements for the coherence atomic_load_explicit. And no surprise, as you suspected, P99 maps that on __sync_val_compare_and_swap(&x, 0, 0). Then if you look into the assembler that this generates on most architectures this will just translate in a simple load operation in the case of x beeing an int. But this is not guaranteed by the language, it is up to the compiler to know such things and to synthesize the instructions that are guaranteed to be atomic.

这篇关于原子比较,多处理器,C/C ++(Linux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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