原子操作有内存顺序问题吗?

问题描述 投票:0回答:0

原子操作之间是否存在

happens before
关系,例如原子也需要内存顺序?代码:

static int zero = 0;

static int proc_enter(struct proc_context* ctx, struct lkf_node* node)
{
    __atomic_store_n(&node->next, NULL, __ATOMIC_RELAXED);  // 0
    __atomic_store_n(&ctx->list.tail, &node->next, __ATOMIC_RELEASE);  // 1


    int n = (int) __atomic_compare_exchange_n(&ctx->stat, &zero, 1, false, __ATOMIC_RELEASE, // 2
                                              __ATOMIC_RELAXED);
    return n - 1;
}

static int proc_leave(struct proc_context* ctx)
{
    __atomic_store_n(&ctx->stat, 0, __ATOMIC_RELAXED);  // 3

    __atomic_thread_fence(__ATOMIC_ACQ_REL); // 4

    if (__atomic_load_n(&ctx->list.tail, __ATOMIC_RELAXED) == &ctx->list.root.next) { // 5
        return 0;
    }

    int n = (int) __atomic_compare_exchange_n(&ctx->stat, &zero, 1, false, __ATOMIC_RELAXED,
                                              __ATOMIC_RELAXED);
    return n - 1;
}

几个问题:

  1. 是否需要__ATOMIC_RELEASE来保证
    // 0
    发生在
    // 1
    之前?
  2. 是否需要 __atomic_compare_exchange_n 中的 __ATOMIC_RELEASE 来保证
    // 1
    // 2
    之前发生?
  3. 是否需要__ATOMIC_ACQ_REL来保证
    // 5
    发生在
    // 3
  4. 之前
  5. __atomic_thread_fence 是保证
    // 5
    发生在
    // 3
    之前的唯一方法吗(如果有效)?

最后一个问题,我的逻辑是:
我需要的是:

  1. 写 ctx->stat
  2. 清空商店队列
  3. 齐平加载队列
  4. 加载 ctx->list.tail

step 3
禁止
step 4
step 2
禁止
step 1
下降

c memory atomic memory-barriers
© www.soinside.com 2019 - 2024. All rights reserved.