如何在一个原子操作中结合比较和更新?

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

我有两个线程,将执行:

_Atomic volatile uint64_t foo;

// returns 1 if it updated foo, 0 if fool already had the new value 
int try_to_update_foo(uint64_t new) {
    if (foo < new) {
        foo = new;
        return 1;
    }
    return 0;
}

我希望

foo < new
比较和
foo = new
赋值操作成为一个原子操作。

即如果两个线程都尝试将 foo 更新为相同的新值,则一个必须返回 1,另一个必须返回 0。(无论哪种方式都没关系。)

我可以在 C11 中完成这项工作,而不涉及信号量/互斥体吗?

linux x86-64 atomic c11
1个回答
0
投票

您可以使用

atomic_compare_exchange_weak()
atomic_compare_exchange_strong()
:

#include <stdatomic.h>

_Atomic uint64_t foo;

int try_to_update_foo(uint64_t new) {
    uint64_t expected = atomic_load(&foo);
    while (expected < new) {
        if (atomic_compare_exchange_strong(&foo, &expected, new)) {
            return 1;
        }
    }
    return 0;
}

有关详细信息,请参阅文档:https://en.cppreference.com/w/c/atomic/atomic_compare_exchange

© www.soinside.com 2019 - 2024. All rights reserved.