如何在 std::atomic 上运行compare_exchange_weak<bool>?

How to run compare_exchange_weak on an std::atomic<bool>?

本文关键字:weak gt lt bool exchange compare std atomic 运行      更新时间:2024-09-29

我试过运行

std::atomic<bool> set(false);

然后在稍后的一个函数中,我尝试使用:

Process::signalsDone.compare_exchange_weak(false, true, std::memory_order_release, std::memory_order_relaxed);

为什么在编译时会出现错误消息?

error C2664: 'bool std::atomic<bool>::compare_exchange_weak(_Ty &,const _Ty,const std::memory_order,const std::memory_order) noexcept': cannot convert argument 1 from 'bool' to '_Ty &'
with
[
_Ty=bool
]
C:Program Files (x86)Microsoft Visual Studio2019ProfessionalVCToolsMSVC14.27.29110includeatomic(1636): note: see declaration of 'std::atomic<bool>::compare_exchange_weak'

compare_exchange_weak的第一个参数是T&

不能将像false这样的文字绑定到T&;你从来没能做到这一点。

相反,创建一个类型为bool的变量,该变量可以通过引用传递给函数。如果比较失败,变量的值将更改为atomic_bool的实际值。