gpt4 book ai didi

c++ - 你能自动写两个 uint64_t 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:25 25 4
gpt4 key购买 nike

我有一个问题,我需要能够自动更新两个 uint64_t的同时。以原子方式编写它们中的每一个是很容易的(例如,有两个 std::atomic<uint64_t> 的),但这仍然会导致更新一个而另一个不更新的情况。使用锁和互斥锁也很容易实现。

但我想以原子方式编写,没有任何类型的锁,这样我仍然可以拥有类型为 uint64_t 的成员变量。这样就不会锁定读取。这是因为我的用例涉及读取它们很多很多次,但很少写入它们(~读取 1x/ms,写入 1x/5 分钟)。可能吗?如果是这样,如何?

最佳答案

对于 std::atomic 标准说(强调我的)

The primary std::atomic template may be instantiated with any TriviallyCopyable type T:

struct Counters { int a; int b; }; // user-defined trivially-copyable type
std::atomic<Counters> cnt; // specialization for the user-defined type

所以你可以只创建一个结构 2 uint64_t像这样

struct atomic128 {
uint64_t a1, a2;
};

这是简单可复制的(很容易用 std::is_trivially_copyable 确认),然后使用 std::atomic<atomic128> .你会得到一个错误 if std::atomic<type> is not trivially copyable

这样编译器将自动使用无锁更新机制(如果可用)。无需执行任何特殊操作,如有必要,只需使用以下任一方法检查即可

All atomic types except for std::atomic_flag may be implemented using mutexes or other locking operations, rather than using the lock-free atomic CPU instructions. Atomic types are also allowed to be sometimes lock-free: for example, if only some subarchitectures support lock-free atomic access for a given type (such as the CMPXCHG16B instruction on x86-64), whether atomics are lock-free may not be known until runtime.

std::atomic_is_lock_free and std::atomic::is_lock_free

Here's a demo在编译器资源管理器上。如您所见lock cmpxchg16b被发出,尽管 GCC 7 和更高版本只会调用 __atomic_store_16哪个internally use cmpxchg16b if it's available

在某些平台上 long double是 128 位类型或被填充为 128 位,因此 std::atomic<long double>可能是另一种解决方案,但当然你需要先检查它的大小以及它是否是无锁的

另一种选择是 Boost.Atomic .它还具有宏 BOOST_ATOMIC_INT128_LOCK_FREE and BOOST_ATOMIC_LONG_DOUBLE_LOCK_FREE 检查

在某些 CPU 上,128 位 SSE 操作也是原子操作,不幸的是,没有办法检查您是否可以使用它

另见:

关于c++ - 你能自动写两个 uint64_t 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com