我有两个线程,将执行:
_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 中完成这项工作,而不涉及信号量/互斥体吗?
您可以使用
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