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

标签 c++ multithreading c++11 atomic

我有以下代码:

#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,

所以我的问题:

  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/

相关文章:

c++ - 在 Linux Qt Creator C++ 中对 char * 使用 malloc 时接收 SIGSEGV 信号

android - Qt android 屏幕锁定java问题

python - 创建大量对象(神经元)并使用字典随机连接

c++ - MFC 将消息发送到主线程(而不是窗口)?

使用默认类型的 C++ 函数引用模板替换错误

c++ - 如何让 QTextBrowser 始终在末尾插入文本

c++ - 取而代之的是获取存储的内存编号

c++ - 在运行时删除未就绪的对象 cpp

c++ - Qt并发: call member function from another class

c++ - 在 [0, n) 中生成随机数