复制构造器中复制原子的非锁定方式 [英] Nonlocking Way to Copy Atomics in Copy Constructor
问题描述
我正在为数据结构编写一个复制构造函数,该结构需要将两个std::atomic<T>
成员复制到一个新对象中.尽管在我的用例中该过程不一定必须是原子的,但我希望有尽可能最正确的解决方案.
I am writing a copy constructor for a data structure which needs to copy two std::atomic<T>
members into a new object. While the process doesn't necessarily have to be atomic in my use-case, I would prefer to have the most correct solution possible.
我知道使用std::atomic<T>
明确删除了复制构造函数,以强制用户使用原子接口.
I am aware that the copy constructor is explicitly deleted with std::atomic<T>
so as to force users to use the atomic interface.
atomic(const atomic&)= delete;
atomic(const atomic&) = delete;
我目前正在做的事情是这样的:
What I am currently I am doing something like this:
SomeObject(const SomeObject& other):
_atomic1(other._atomic1.load()),
_atomic2(other._atomic2.load()) {
...
}
我不认为此操作是原子操作,也不知道一种实现方法(没有锁).
I do not believe this operation is atomic, nor do I know a way to make is so (without locks).
有没有办法自动复制这些值(不带锁)?
Is there a way to copy these values atomically (without locks)?
推荐答案
唯一的方法是制作包含两个T
的普通可复制结构S
并使用std::atomic<S>
.
The only way is to make a trivially copyable struct S
containing two T
s and use std::atomic<S>
.
请注意,仅当您从一开始就使用此S
时,此方法才有效-无法无锁地原子加载两个单独的原子.
Note that this only works if you've been using this S
from the start - there is no way to atomically load two separate atomics without locks.
所以代替:
struct SomeObject {
SomeObject(const SomeObject& other) : i(other.i.load()), j(other.j.load()) { }
std::atomic<int> i, j;
};
执行此操作:
struct SomeObject {
SomeObject(const SomeObject& other) : data(other.data.load()) { }
struct Data { int i, j; };
std::atomic<Data> data;
};
请注意,这可能(可能会)仍在内部使用锁.使用 is_lock_free
进行检查.
Note that this might (probably will) still use locks internally. Use is_lock_free
to check if it does.
这篇关于复制构造器中复制原子的非锁定方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!