求问Windows InterlockedExchange的POSIX等效跨平台跨架构C语言实现
跨平台实现Windows InterlockedExchange的等效原子操作
嘿,刚好我之前研究过这个问题,给你两个不需要手写汇编、能跨平台跨架构的C实现方案,完美替代Windows的InterlockedExchange:
方案1:用GCC内置函数(兼容旧编译器)
你已经找到了InterlockedCompareExchange的等效__sync_val_compare_and_swap,那对于原子交换,GCC其实有更直接的内置函数__sync_lock_test_and_set——它的作用就是原子地把目标内存的值替换成新值,同时返回原来的旧值,完全匹配InterlockedExchange的语义。我们可以封装成和Windows接口一致的函数,方便直接替换:
#include <stdint.h> // 32位整数版本,和Windows InterlockedExchange接口对齐 static inline uint32_t InterlockedExchange(uint32_t *target, uint32_t newValue) { return __sync_lock_test_and_set(target, newValue); } // 64位整数版本 static inline uint64_t InterlockedExchange64(uint64_t *target, uint64_t newValue) { return __sync_lock_test_and_set(target, newValue); }
这个内置函数在GCC支持的主流架构(x86、ARM、PowerPC等)上都有实现,不用自己写汇编,直接就能用。
方案2:用C11标准原子库(更推荐,长期兼容)
如果你的编译器支持C11(现在GCC、Clang、MSVC这些主流编译器都支持),更推荐用标准的<stdatomic.h>库来实现,这是C语言官方的原子操作标准,跨平台兼容性更好,代码也更规范:
#include <stdatomic.h> #include <stdint.h> // 32位版本 static inline uint32_t InterlockedExchange(uint32_t *target, uint32_t newValue) { return atomic_exchange((atomic_uint32_t*)target, newValue); } // 64位版本 static inline uint64_t InterlockedExchange64(uint64_t *target, uint64_t newValue) { return atomic_exchange((atomic_uint64_t*)target, newValue); }
要是需要针对指针的原子交换(对应Windows的InterlockedExchangePointer),只要把函数里的类型换成void*就行,两种方案都支持指针类型的原子操作。
内容的提问来源于stack exchange,提问作者Nick Banks
相关产品推荐
相关产品推荐

