尽管数据匹配期望值,但compare_exchange_strong仍失败 [英] compare_exchange_strong failing despite data matching expected value

查看:141
本文介绍了尽管数据匹配期望值,但compare_exchange_strong仍失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是 compare_exchange_strong 返回false,尽管基础数据等于预期。例如:

The issue is with a compare_exchange_strong returning false, despite the underlying data being equal to expected. e.g.:

std::atomic<data> ptr;
...
auto ptr_data = ptr.load();
bool cmp_result = memcmp(&ptr_data, &expected, sizeof(ptr_data));
bool cas_result = ptr.compare_exchange_strong(expected, desired);
assert(cas_result || !cmp_result);

data 是128位POD。 ptr.is_lock_free()返回true。这以单线程方式进行了测试。 cas_result 始终为假, cmp_results 始终为真。

data is a 128-bit POD. ptr.is_lock_free() returns true. This is tested in a single-threaded fashion. cas_result is always false, cmp_results always true.

编译是使用Intel的C ++编译器(版本16更新2)完成的。在Linux上,libstdc ++版本5.3.1。 64位二进制文​​件。
与在Windows上编译时使用的完全相同的代码,具有相同的ICC16,但为32位代码。这使我相信这是stdlib实现的怪癖。

Compilation is done with Intel's C++ compiler, version 16 update 2. On Linux, libstdc++ version 5.3.1. 64-bit binary.
Exactly the same code used to work correctly when compiled on Windows, with same ICC16 but as 32-bit code. This makes me believe it is the stdlib implementation quirk.

谢谢

推荐答案

我在使用的结构上也遇到过这种情况。我认为这是由于对齐问题而插入填充位以及compare_exchange对两个值进行按位比较的结果。

I've had this situation as well on a struct I was using. I think it was caused by padding bits inserted due to alignment issues and the fact that compare_exchange does a bitwise comparison of the two values.

在我的机器上,字/指针的大小为8个字节而我拥有的结构是这样的:

On my machine, the word/pointer size is 8 bytes and the struct I had was something like this:

struct s {
    int i;
    void *ptr;

};

仅使用12个字节来表示其内容(ptr为8个字节,int为4),但其大小为16个字节(sizeof(s)== 16)。我所做的就是将结构更改为:

which used only 12 bytes to represent its contents (ptr was 8 bytes, int was 4), but it's size was of 16 bytes (sizeof(s) == 16). What I did was change the struct into:

struct s {
    long long i;
    void *ptr;
};

由于long long在我的机器上是8个字节,因此该版本的大小为16个字节,它们都用来表示实际值(无填充位)。

Because long long is 8 bytes on my machine, this version had a 16 bytes size and they were all used to represent the actual value (no padding bits).

在阅读后,我看到了问题答案,可能会更详细。

I saw the problem after reading this answer, which might be more detailed.

这篇关于尽管数据匹配期望值,但compare_exchange_strong仍失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆