1

我知道在 MacOSX / PosiX 系统上,通过 g++ 对 C/C++ 代码进行原子比较和交换。

但是,我不需要比较——我只想原子地交换两个值。是否有可用的原子交换操作?[我能找到的所有东西都是 atomic_compare_and_swap ...我只想进行交换,而不进行比较]。

谢谢!

4

3 回答 3

3

“lock xchg” intel 汇编指令可能实现了您想要的,但我认为没有 GCC 包装函数可以使其可移植。因此,您使用内联汇编(不可移植)或使用比较和交换并强制比较为真(无效)。希望这可以帮助 :-)

于 2010-03-12T23:42:36.337 回答
1

GCC 确实在某些处理器上提供了此操作,在 (混淆命名) 下__sync_lock_test_and_set。从 GCC 文档:

 This builtin, as described by Intel, is not a traditional
 test-and-set operation, but rather an atomic exchange operation.
 It writes VALUE into `*PTR', and returns the previous contents of
 `*PTR'.

 Many targets have only minimal support for such locks, and do not
 support a full exchange operation.  In this case, a target may
 support reduced functionality here by which the _only_ valid value
 to store is the immediate constant 1.  The exact value actually
 stored in `*PTR' is implementation defined.

但是,x86-32 和 x86-64 支持完全交换操作,有效地提供了lock xchg您需要编写的包装器。

于 2012-10-09T14:55:10.427 回答
0

不要认为有。这是参考,顺便说一句:http: //developer.apple.com/Mac/library/documentation/DriversKernelHardware/Reference/libkern_ref/OSAtomic_h/index.html#//apple_ref/doc/header/user_space_OSAtomic.h

于 2010-03-12T23:40:52.013 回答