本文介绍了C ++ 11:atomic :: compare_exchange_weak是否支持非原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#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的none-lock函数是否可以用于复杂的数据结构.用--std = c ++ 11编译,它给了我:

Well, atomic works well, but I wish to see if none-lock function of compare_exchange_weak could work for complex data structures. Compiled with --std=c++11 it gives me:

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. std :: atomic :: compare_exchange_weak是否适用于复杂的结构?

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

如果intel cpu硬件CMPEXG仅在64位长的缓存行内工作,大于8字节的结构是否可以与CMPEXG一起工作?还是原子操作?

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?

如何修复我的程序?

谢谢.

推荐答案

是的,但是有条件,其中包括可轻松复制完全可构造.

Yes, but there are conditions that include trivially copyable and trivially constructible.

不.那样行不通.如果您创建疯狂的大型结构(如您所拥有的结构),您的代码将不会无锁".您的编译器将发出总线锁以确保线程安全,这就是为什么您永远不要使用大数据结构来执行您正在做的事情.您将使程序减慢数百倍,甚至更多.考虑原子交换指针.

No. It doesn't work that way. If you create crazily big structures like the one you have there, your code will not be "lockfree". Your compiler will issue bus-locks to ensure thread-safety, which is why you should never, ever do what you're doing up there with big data strucutres. You'll slow down your program by hundreds of times, if not more. Consider atomically exchanging pointers.

不,它使用锁.您可以使用 std::atomic::is_lock_free()

No, it uses locks. You can test this with std::atomic::is_lock_free()

去那里:

#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是否支持非原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 13:07