问题描述
准确地说,我只需要再增加一个双精度值,并希望它是线程安全的即可.我不想为此使用互斥锁,因为执行速度会大大降低.
To be precise, I only need to increase a double by another double and want it to be thread safe. I don't want to use mutex for that since the execution speed would dramatically decrease.
推荐答案
通常,C ++标准库尝试仅提供可以有效实现的操作.对于std::atomic
,这意味着可以在通用"体系结构中的一条指令或两条指令中无锁执行操作. 通用"体系结构具有用于整数的原子获取和添加指令,但不适用于浮点类型.
As a rule, the C++ standard library tries to provide only operations that can be implemented efficiently. For std::atomic
, that means operations that can be performed lock-free in an instruction or two on "common" architectures. "Common" architectures have atomic fetch-and-add instructions for integers, but not for floating point types.
如果要为原子浮点类型实现数学运算,则必须自己进行CAS(比较和交换)循环(在Coliru直播):
If you want to implement math operations for atomic floating point types, you'll have to do so yourself with a CAS (compare and swap) loop (Live at Coliru):
std::atomic<double> foo{0};
void add_to_foo(double bar) {
auto current = foo.load();
while (!foo.compare_exchange_weak(current, current + bar))
;
}
这篇关于当类型不是整数时,如何使用std :: atomic执行基本操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!