我有以下代码:
#include<atomic>
#include<iostream>
using namespace std;
struct Big{
int i;
int j;
int k[100];
};
int main(){
atomic<int> i;
cout<<i.load()<<endl;
i.store(20);
cout<<i.load()<<endl;
i.exchange(30);
cout<<i.load()<<endl;
atomic<Big> ab,expect,value;
ab.compare_exchange_weak(expect,value,memory_order_release,memory_order_relaxed);//error
return 0;
}
嗯,原子工作得很好,但我想看看compare_exchange_weak的无锁函数是否可以用于复杂的数据结构。使用 --std=c++11 编译它给了我:
error: no matching member function for call to 'compare_exchange_weak'
ab.compare_exchange_weak(expect,value,memory_order_release,memory_order_relaxed);
~~~^~~~~~~~~~~~~~~~~~~~~
candidate function not viable: no known conversion from 'atomic<Big>' to 'Big &' for 1st argument
bool compare_exchange_weak(_Tp& __e, _Tp __d,
所以我的问题:
Does std::atomic::compare_exchange_weak work with complex structures?
If intel cpu hardware CMPEXG only works within 64 bit length cache line, does structures larger than 8 bytes work with CMPEXG? Is it still atomic operation?
How to fix my program?
谢谢。
最佳答案
Does std::atomic::compare_exchange_weak work with complex structures?
是的,但是有 conditions其中包括trivially copyable和 trivially constructible .
If intel cpu hardware CMPEXG only works within 64 bit length cache line, does structures larger than 8 bytes work with CMPEXG?
没有。事实并非如此。如果您创建像您那里那样的疯狂大结构,您的代码将不会是“无锁”的。您的编译器将发出总线锁以确保线程安全,这就是为什么您永远不应该对大数据结构执行您正在做的事情。你的程序速度将会减慢数百倍甚至更多。考虑以原子方式交换指针。
Is it still atomic operation?
不,它使用锁。您可以使用 std::atomic::is_lock_free()
进行测试
How to fix my program?
给你:
#include <atomic>
#include <iostream>
using namespace std;
struct Big {
int i;
int j;
int k[100];
};
int main() {
Big value, expect;
atomic<Big> ab;
ab.compare_exchange_weak(expect, value);
return 0;
}
关于C++11:atomic::compare_exchange_weak 是否支持非原始类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45346054/