compiler_barrier 作用

在需要确保操作顺序但不需要完整内存屏障的情况下,编译器屏障提供了轻量级的解决方案。

例子代码

#include <stdio.h>
#include <stdatomic.h>

// 编译器屏障的常见实现方式
#ifdef _MSC_VER
    #include <intrin.h>
    #define compiler_barrier() _ReadWriteBarrier()
#else
    #define compiler_barrier() __asm__ __volatile__("" ::: "memory")
#endif

int main() {
    int x = 0;
    int y = 0;
    
    x = 5;
    
    // 插入编译器屏障
    compiler_barrier();
    
    y = 10;
    
    printf("x = %d, y = %d\n", x, y);
    
    // 多线程示例
    _Atomic int flag = 0;
    int data = 0;
    
    // 线程1:写入数据后设置标志
    data = 42;
    compiler_barrier(); // 确保数据写入在标志设置之前
    flag = 1;
    
    // 线程2:检查标志后读取数据
    while (flag == 0) {
        // 等待
    }
    compiler_barrier(); // 确保在读取数据前标志已更新
    printf("Data: %d\n", data);
    
    return 0;
}

// Functions for portable atomic access. // To abstract locking primitives across all thread policies, use: // __exchange_and_add_dispatch // __atomic_add_dispatch #ifdef _GLIBCXX_ATOMIC_BUILTINS_4 static inline _Atomic_word __exchange_and_add(volatile _Atomic_word* __mem, int __val) { return __sync_fetch_and_add(__mem, __val); } static inline void __atomic_add(volatile _Atomic_word* __mem, int __val) { __sync_fetch_and_add(__mem, __val); } #else _Atomic_word __attribute__ ((__unused__)) __exchange_and_add(volatile _Atomic_word*, int); void __attribute__ ((__unused__)) __atomic_add(volatile _Atomic_word*, int); #endif static inline _Atomic_word __exchange_and_add_single(_Atomic_word* __mem, int __val) { _Atomic_word __result = *__mem; *__mem += __val; return __result; } static inline void __atomic_add_single(_Atomic_word* __mem, int __val) { *__mem += __val; } static inline _Atomic_word __attribute__ ((__unused__)) __exchange_and_add_dispatch(_Atomic_word* __mem, int __val) { #ifdef __GTHREADS if (__gthread_active_p()) return __exchange_and_add(__mem, __val); else return __exchange_and_add_single(__mem, __val); #else return __exchange_and_add_single(__mem, __val); #endif } static inline void __attribute__ ((__unused__)) __atomic_add_dispatch(_Atomic_word* __mem, int __val) { #ifdef __GTHREADS if (__gthread_active_p()) __atomic_add(__mem, __val); else __atomic_add_single(__mem, __val); #else __atomic_add_single(__mem, __val); #endif } _GLIBCXX_END_NAMESPACE // Even if the CPU doesn't need a memory barrier, we need to ensure // that the compiler doesn't reorder memory accesses across the // barriers. #ifndef _GLIBCXX_READ_MEM_BARRIER #define _GLIBCXX_READ_MEM_BARRIER __asm __volatile ("":::"memory") #endif #ifndef _GLIBCXX_WRITE_MEM_BARRIER #define _GLIBCXX_WRITE_MEM_BARRIER __asm __volatile ("":::"memory") #endif #endif
最新发布
09-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值