gpt4 book ai didi

C++11:atomic::compare_exchange_weak 是否支持非原始类型?

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:38 27 4
gpt4 key购买 nike

我有以下代码:

#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;
}

好吧,atomic 工作得很好,但我想看看 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,

所以我的问题是:

  1. Does std::atomic::compare_exchange_weak work with complex structures?

  2. 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?

  3. How to fix my program?

谢谢。

最佳答案

Does std::atomic::compare_exchange_weak work with complex structures?

是的,但是有 conditions包括trivially copyabletrivially 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com