问题描述
- 我想将
std::compare_exchange_strong
用于std::atomic<int>
- 出于编译原因(
int &
),我不得不介绍int _OLD_VALUE = OLD_VALUE
。 - 有没有更优雅的方法来实现这一目标?
- 这是我的例子
#include <atomic>
#include <stdio.h>
#define OLD_VALUE 16
#define NEW_VALUE 744
#define OTHER_VALUE 80
int main(int argc,char **argv)
{
std::atomic<int> i(OTHER_VALUE);
int _OLD_VALUE = OLD_VALUE;
bool status = i.compare_exchange_strong(_OLD_VALUE,NEW_VALUE);
// bool status = i.compare_exchange_strong( OLD_VALUE,NEW_VALUE);
if (status) { printf("good\n"); }
return 0;
}
这是使用注释版本时的编译错误:
main.cpp: In function ‘int main(int,char**)’:
main.cpp:11:65: error: cannot bind non-const lvalue reference of type ‘std::__atomic_base<int>::__int_type& {aka int&}’ to an rvalue of type ‘int’
bool status = i.compare_exchange_strong( OLD_VALUE,NEW_VALUE);
^
In file included from /usr/include/c++/7/atomic:41:0,from main.cpp:1:
/usr/include/c++/7/bits/atomic_base.h:496:7: note: initializing argument 1 of ‘bool std::__atomic_base<_IntTp>::compare_exchange_strong(std::__atomic_base<_IntTp>::__int_type&,std::__atomic_base<_IntTp>::__int_type,std::memory_order) [with _ITp = int; std::__atomic_base<_IntTp>::__int_type = int; std::memory_order = std::memory_order]’
compare_exchange_strong(__int_type& __i1,__int_type __i2,^~~~~~~~~~~~~~~~~~~~~~~
解决方法
不。原因是交换了变量的先前值,因此如果比较不匹配,则$('.FileUpload').html(fileName);
值将被覆盖。
要了解幕后情况,请查看GCC内置组件: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
您会注意到,GCC(Linux)的内置文件中有一个expected
,但它只是提供了交换,而不是比较和交换。 Windows等效为__atomic_exchange_n
:https://docs.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedexchange
出于可读性考虑,我将避免在变量名称中使用大写字母,并避免在下划线前添加
InterlockedExchange
,
实现这一目标的最简单方法(我想是唯一方法)是编写简单的包装器:
bool cas_strong(std::atomic<int>& a,int cmp,int exc) {
return a.compare_exchange_strong(cmp,exc);
}
,
compare_exchange_strong
期望int&
存储在i
中找到的当前值。在这里,您间接提供16
(这是在预处理过程中宏OLD_VALUE
所替换的),它是一个整数编译时常数,也就是constexpr int&
。这与int&
不兼容。
要提供int&
,您最好在通话int
附近保持compare_exchange_strong
:
std::atomic<int> i(OTHER_VALUE);
int old_value = OLD_VALUE;
bool status = i.compare_exchange_strong(old_value,NEW_VALUE);
if (status) { printf("good\n"); }
return 0;
此外,更一般而言,如果您在此处使用静态常量而不是宏,则显然更强大。 关于这个其他问题的更多信息:What is the difference between a macro and a const in C++?
,不要使用宏来定义值:
#include <atomic>
#include <stdio.h>
int OLD_VALUE 16
int NEW_VALUE 744
int OTHER_VALUE 80
int main(int argc,char **argv)
{
std::atomic<int> i(OTHER_VALUE);
bool status = i.compare_exchange_strong( OLD_VALUE,NEW_VALUE);
if (status) { printf("good\n"); }
return 0;
}