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

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

谢谢!

有帮助吗?

解决方案

“锁定XCHG” Intel汇编指令可能达到你想要的东西,但我不认为这是一个GCC的包装功能,使其便于携带。为此您使用内联汇编(不可移植),或者使用比较和交换,迫使比较为真(inneficient)卡。希望这有助于: - )

其他提示

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包装,否则你需要编写。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top