C ++ 11 std :: atomic_fetch_add与__sync_fetch_and_add [英] C++11 std::atomic_fetch_add vs __sync_fetch_and_add

查看:187
本文介绍了C ++ 11 std :: atomic_fetch_add与__sync_fetch_and_add的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前无法正确理解新的 std :: atomic 类型的用法.就我而言,我有以下假设:

I'm currently having troubles correctly understanding the usage of the new std::atomic types. For my case I have the following assumptions:

  1. 我在内存中存储了 uint64_t 值的连续存储位置
  2. 我有两种访问方式:简单增量和原子增量

最初我实现了这样的方法

Originally I implemented the methods like this

uint64_t inc(const size_t pos) { return _data[pos]++; }
uint64_t atomic_inc(const size_t pos) { return __sync_fetch_and_add(&_data[pos], 1); }

现在,我想将其正确移植到C ++ 11,并且想知道如何正确处理它.根据我对 std :: atomic_fetch_add 的理解,一个基本需要原子整数值来完成这.但是,我该如何正确实现它,以便可以使用原子变量指向某个位置并增加该值?

Now I wanted to port this correctly to C++11 and was wondering how should I handle this correctly. From my understanding of std::atomic_fetch_add one basically needs an atomic integral value to do this. However, how do I need to implement this correctly, so that I can point using an atomic variable to a location and increment the value?

谢谢!

推荐答案

您不能.

C ++ 11原子对象封装其基本类型.它不提供对作为lvalue的值的访问,也不能将其设置为对基础类型的预先存在的对象(在给定的内存位置)提供原子操作.

A C++11 atomic object encapsulates its base type. It does not provide access to its value as lvalue nor can you set it up to provide atomic operations on a preexisting object of the underlying type (at a given memory location).

取决于平台,任何给定的原子类型可能有特殊要求(例如,更严格的对齐约束)或需要辅助数据(大多数原子类型不能保证没有锁)

Depending on the platform any given atomic type might have special requirements (e.g. stronger alignment constraints) or need auxiliary data (most atomic types are not guaranteed to be lock-free)

要做您想做的事仍然需要特定于平台的功能.

Doing what you want to do still requires platform-specific functionality.

如果要进行非原子增量,则可以得到的最接近值是:

If you want to do non-atomic increments,the closest you can get is:

  atomic<uint64_t> data(initial_value);
  data.store(data.load(memory_order_relaxed) + 1, memory_order_relaxed);

这仍将执行原子加载和存储,但不执行内存隔离或原子读取-修改-写入操作.

This will still do atomic loads and stores, but no memory fencing or atomic read-modify-write operations.

这篇关于C ++ 11 std :: atomic_fetch_add与__sync_fetch_and_add的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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